예제 #1
0
    def clean(self):
        cleaned_data = super(TicketForm,self).clean()

        gotten_phone_number = cleaned_data.get('phone_number')

        if gotten_phone_number[:4] == '+254':
            string_to_phonenumber = phonenumbers.parse(gotten_phone_number,"KE")

            print(len(gotten_phone_number))

            if phonenumbers.is_possible_number(string_to_phonenumber) != True or len(gotten_phone_number)!=13:

                print("This is not a valid phone number!")
                raise forms.ValidationError('This is not a valid Kenyan phone number!')
        elif gotten_phone_number[:2]=="07":

            without_zero = gotten_phone_number[1:]

            add_country_code = '+254'+without_zero

            string_to_phonenumber = phonenumbers.parse(add_country_code,'KE')

            if phonenumbers.is_possible_number(string_to_phonenumber) != True or len(add_country_code)!=13:

                raise forms.ValidationError("This is not a valid Kenyan phone number!")
        else:

            raise forms.ValidationError("This is not a valid Kenyan phone number!")

        return cleaned_data


        
예제 #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))
예제 #3
0
 def to_internal_value(self, data):
     phone_number = to_python(data)
     if phone_number and not phonenumbers.is_possible_number(phone_number):
         # attempting to check if this is a possible Indian number
         phone_number = to_python(data, region="IN")
         if phone_number and not phonenumbers.is_possible_number(
                 phone_number):
             raise ValidationError(self.error_messages["invalid"])
     return phone_number
예제 #4
0
파일: forms.py 프로젝트: mohman23/bus-board
    def clean(self):

        cleaned_data = super(TicketForm, self).clean()

        gotten_phone_number = cleaned_data.get('phone_number')

        # Check if phone number begins with the Kenyan country code
        if gotten_phone_number[:4] == '+254':

            # print('country code detected')

            # Convert string to phone number
            string_to_phonenumber = phonenumbers.parse(gotten_phone_number,
                                                       "KE")

            print(len(gotten_phone_number))

            # Check if the phonenumber is not a valid Kenyan number
            if phonenumbers.is_possible_number(
                    string_to_phonenumber) != True or len(
                        gotten_phone_number) != 13:

                # print('Not a valid Kenyan number')
                raise forms.ValidationError(
                    'The phone number is not a valid Kenyan phone number')

        # Check if the number begins with a 0
        elif gotten_phone_number[:2] == '07':

            # print('number without country code')

            # Phone number string without 0
            without_zero = gotten_phone_number[1:]

            # Add Kenyan country code to the beginning
            add_country_code = '+254' + without_zero

            # Convert string to phone number
            string_to_phonenumber = phonenumbers.parse(add_country_code, "KE")

            # Check if the phonenumber is not a valid Kenyan number
            if phonenumbers.is_possible_number(
                    string_to_phonenumber) != True or len(
                        add_country_code) != 13:

                # print('Not a valid Kenyan number')
                raise forms.ValidationError(
                    'The phone number is not a valid Kenyan phone number')

        # Otherwise
        else:

            # print('number with non-Kenyan country code')
            raise forms.ValidationError(
                'The phone number is not a valid Kenyan phone number')

        return cleaned_data
예제 #5
0
    def validate_phone(self, phone):
        try:
            number = phonenumbers.parse(phone.data, None)
            if not phonenumbers.is_possible_number(number):
                raise ValidationError('Invalid phone number.')

        except:
            number = phonenumbers.parse("+1" + phone.data, None)
            if not phonenumbers.is_possible_number(number):
                raise ValidationError('Invalid phone number.')
예제 #6
0
 def checkphonenumbers(matched):
     for phone_number in matched:
         try:
             z = phonenumbers.parse(phone_number, "IN")
             if phonenumbers.is_possible_number(z) and phonenumbers.is_valid_number(z):
                 print "Possible %s, Valid %s, Explain: %s" % (phonenumbers.is_possible_number(z), phonenumbers.is_valid_number(z), z)
                 return True
         except phonenumbers.phonenumberutil.NumberParseException:
             pass
     return False
예제 #7
0
 def number_validity_check(self, number, country):
     try:
         self.parsed_number = phonenumbers.parse(number, country)
         phonenumbers.is_valid_number(self.parsed_number)
         phonenumbers.is_possible_number(self.parsed_number)
         return True
     except phonenumbers.NumberParseException:
         print(
             '[-] Please provide the following phone number in International format or provide Region',
             number)
         return False
예제 #8
0
 def checkphonenumbers(matched):
     test_formats = [ "IN", "US", None ]
     for phone_number in matched:
         for testf in test_formats:
             try:
                 z = phonenumbers.parse(phone_number, testf)
                 if phonenumbers.is_possible_number(z) and phonenumbers.is_valid_number(z):
                     print "Possible %s, Valid %s, Explain: %s" % (phonenumbers.is_possible_number(z), phonenumbers.is_valid_number(z), z)
                     return True
             except phonenumbers.phonenumberutil.NumberParseException:
                 pass
     return False
예제 #9
0
 def check_phone_numbers(matched):
     test_formats = ["IN", "US", None]
     for phone_number in matched:
         for testf in test_formats:
             try:
                 z = phonenumbers.parse(phone_number, testf)
                 if phonenumbers.is_possible_number(z) and phonenumbers.is_valid_number(z):
                     print "Possible %s, Valid %s, Explain: %s" % (phonenumbers.is_possible_number(z), phonenumbers.is_valid_number(z), z)
                     return True
             except phonenumbers.phonenumberutil.NumberParseException:
                 pass
     return False
예제 #10
0
 def check_phone_numbers(matched):
     test_formats = ["IN", "US", None]
     for phone_number in matched:
         if regex.compile(r"^21474672[56]\d$").search(phone_number):
             return False
         for testf in test_formats:
             try:
                 z = phonenumbers.parse(phone_number, testf)
                 if phonenumbers.is_possible_number(z) and phonenumbers.is_valid_number(z):
                     print "Possible %s, Valid %s, Explain: %s" % (phonenumbers.is_possible_number(z), phonenumbers.is_valid_number(z), z)
                     return True
             except phonenumbers.phonenumberutil.NumberParseException:
                 pass
     return False
예제 #11
0
 def check_phone_numbers(matched):
     test_formats = ["IN", "US", None]
     for phone_number in matched:
         if regex.compile(r"^21474672[56]\d$").search(phone_number):
             return False
         for testf in test_formats:
             try:
                 z = phonenumbers.parse(phone_number, testf)
                 if phonenumbers.is_possible_number(z) and phonenumbers.is_valid_number(z):
                     print "Possible {}, Valid {}, Explain: {}".format(phonenumbers.is_possible_number(z), phonenumbers.is_valid_number(z), z)
                     return True
             except phonenumbers.phonenumberutil.NumberParseException:
                 pass
     return False
예제 #12
0
def phonenumber_lookup(ph):
    try:
        number = phonenumbers.parse(ph)
        phonenumbers.is_possible_number(number)
        print("Country: " + geocoder.region_code_for_number(number))
        if geocoder.description_for_number(number, "en").lstrip() != "":
            print("City: " + geocoder.description_for_number(number, "en"))
        print(
            "Timezone: " +
            re.sub("[()'',]", "", str(timezone.time_zones_for_number(number))))
        print("Carrier: " + carrier.name_for_number(number, "en"))
    except phonenumbers.phonenumberutil.NumberParseException:
        cprint(error, "Invalid or malformed number.")
        return
예제 #13
0
def validate_phone_number(phone_number: str = ''):
    try:
        if not phone_number:
            return 'Missing phone number', -4
        if type(phone_number) != str:
            return "Unable to determine phone number", -4
        region = "KE"
        # Create a `PhoneNumber` object from a string representing a phone number
        # Specify country of origin of phone number.
        # This maybe unnecessary for numbers starting with '+' since they are globally unique.
        parsed_phone = phonenumbers.parse(phone_number, region)
        # Check whether it's a possible number (e.g. it has the right number of digits)
        if not phonenumbers.is_possible_number(parsed_phone):
            return "Possibly not a number. Check if e.g. number of digits is correct", -4
        # Check whether it's a valid number (e.g. it's in an assigned exchange)
        if not phonenumbers.is_valid_number_for_region(parsed_phone, region):
            return "Invalid phone number", -4
        # Format number as per international format code E164
        phone_number = phonenumbers.format_number(
            parsed_phone, phonenumbers.PhoneNumberFormat.E164)
        # Get the carrier of the phone number
        operator = carrier.name_for_number(parsed_phone,
                                           "en") if carrier.name_for_number(
                                               parsed_phone, "en") else ''
        return f"""Phone number valid. Phone: {phone_number}. Operator: {operator}""", 0
    except phonenumbers.phonenumberutil.NumberParseException as err:
        return f'{err}', -4
    except BaseException as ex:
        return f'{ex}', -4
예제 #14
0
def numberScan():
    global phoneNumberGET, phoneNumber, numberNSCAN, numberCC, numberC, numberLOCAL, numberINTER, countryNSCAN, locationNSCAN, carrierNameNSCAN
    phoneNumberGET = numberSCANentryVar.get()
    #GET INFORMATIONS - PHONE NUMBER SCANNER FRAME
    phoneNumber = phonenumbers.parse(phoneNumberGET, None)
    numberNSCAN = phonenumbers.format_number(
        phoneNumber, phonenumbers.PhoneNumberFormat.E164).replace('+', '')
    numberCC = phonenumbers.format_number(
        phoneNumber,
        phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0]
    numberC = phonenumbers.region_code_for_country_code(int(numberCC))
    numberLOCAL = phonenumbers.format_number(
        phoneNumber,
        phonenumbers.PhoneNumberFormat.E164).replace(numberCC, '')
    numberINTER = phonenumbers.format_number(
        phoneNumber, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
    countryNSCAN = geocoder.country_name_for_number(phoneNumber, 'en')
    locationNSCAN = geocoder.description_for_number(phoneNumber, 'en')
    carrierNameNSCAN = carrier.name_for_number(phoneNumber, 'en')
    #APPLY RESULTS - PHONE NUMBER SCANNER FRAME
    numberReset()
    numberSCANentryVar.set(phoneNumberGET)
    localNSCANentryVar.set(numberLOCAL)
    interNSCANentryVar.set(numberINTER)
    countryNSCANentryVar.set("{} ({})".format(countryNSCAN, numberCC))
    areaNSCANentryVar.set(locationNSCAN)
    carrierNSCANentryVar.set(carrierNameNSCAN)
    for timezoneResult in timezone.time_zones_for_number(phoneNumber):
        timezoneNSCANentryVar.set(timezoneResult)
    if phonenumbers.is_possible_number(phoneNumber):
        validNSCANentryVar.set("VALID+POSSIBLE")
    else:
        validNSCANentryVar.set("INVALID")
예제 #15
0
def localScan(InputNumber, print_results=True):
    print("Running local scan...")

    FormattedPhoneNumber = "+" + formatNumber(InputNumber)

    try:
        PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None)
    except Exception as e:
        print(e)
    else:
        if not phonenumbers.is_valid_number(PhoneNumberObject):
            return False

        number = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164
        ).replace("+", "")
        numberCountryCode = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL
        ).split(" ")[0]
        numberCountry = phonenumbers.region_code_for_country_code(
            int(numberCountryCode)
        )

        localNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164
        ).replace(numberCountryCode, "")
        internationalNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL
        )

        country = geocoder.country_name_for_number(PhoneNumberObject, "en")
        location = geocoder.description_for_number(PhoneNumberObject, "en")
        carrierName = carrier.name_for_number(PhoneNumberObject, "en")

        if print_results:
            print("International format: {}".format(internationalNumber))
            print("Local format: {}".format(localNumber))
            print("Country found: {} ({})".format(country, numberCountryCode))
            print("City/Area: {}".format(location))
            print("Carrier: {}".format(carrierName))
            for timezoneResult in timezone.time_zones_for_number(PhoneNumberObject):
                print("Timezone: {}".format(timezoneResult))

            if phonenumbers.is_possible_number(PhoneNumberObject):
                print("The number is valid and possible.")
            else:
                print("The number is valid but might not be possible.")

    numberObj = {}
    numberObj["input"] = InputNumber
    numberObj["default"] = number
    numberObj["local"] = localNumber
    numberObj["international"] = internationalNumber
    numberObj["country"] = country
    numberObj["countryCode"] = numberCountryCode
    numberObj["countryIsoCode"] = numberCountry
    numberObj["location"] = location
    numberObj["carrier"] = carrierName

    return numberObj
예제 #16
0
def format_e164(number, country_code="NO"):
    """
    Takes a phone number as input and returns it in E.164 format.

    - Returns valid phone numbers on the E.164 format
    ("+<Country code><phone number>").
    - Returns None if there is a problem when parsing the number.

    :param string number:
        Phone number to convert.
    :param string country_code:
        Country code to use as default. Default value is 'NO'
    """
    try:
        res = phonenumbers.parse(number, country_code)
    except phonenumbers.phonenumberutil.NumberParseException as e:
        logger.warning("Problem when parsing %r: %s", number, e)
        return None

    if phonenumbers.is_possible_number(res):
        return phonenumbers.format_number(res,
                                          phonenumbers.PhoneNumberFormat.E164)
    else:
        logger.warning("'%s' is not an accepted number", number)
        return None
예제 #17
0
        def clean_phone_number(self):
            number = self.cleaned_data["phone_number"]

            if "channel" in self.cleaned_data:
                channel = self.cleaned_data["channel"]

                # ensure number is valid for the channel's country
                try:
                    normalized = phonenumbers.parse(number,
                                                    channel.country.code)
                    if not phonenumbers.is_possible_number(normalized):
                        raise forms.ValidationError(
                            _("Invalid phone number, try again."))
                except Exception:  # pragma: no cover
                    raise forms.ValidationError(
                        _("Invalid phone number, try again."))

                number = phonenumbers.format_number(
                    normalized, phonenumbers.PhoneNumberFormat.E164)

                # ensure no other active channel has this number
                if self.org.channels.filter(
                        address=number,
                        is_active=True).exclude(pk=channel.pk).exists():
                    raise forms.ValidationError(
                        _("Another channel has this number. Please remove that channel first."
                          ))

            return number
예제 #18
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
예제 #19
0
def audit_phone(phone_number_types, number):
    if number.startswith("+"):
        number = number[1:]
    z = phonenumbers.parse(number, "US")
    v = phonenumbers.is_possible_number(z)
    if not v:
        phone_number_types.append(number)
예제 #20
0
def normalize_number(number, country_code):
    """
    Normalizes the passed in number, they should be only digits, some backends prepend + and
    maybe crazy users put in dashes or parentheses in the console.
    :param number: the number, e.g. "0783835665"
    :param country_code: the 2-letter country code, e.g. "RW"
    :return: a tuple of the normalized number and whether it looks like a possible full international number
    """
    # if the number ends with e11, then that is Excel corrupting it, remove it
    if number.lower().endswith("e+11") or number.lower().endswith("e+12"):
        number = number[0:-4].replace('.', '')

    # remove other characters
    number = regex.sub('[^0-9a-z\+]', '', number.lower(), regex.V0)

    # add on a plus if it looks like it could be a fully qualified number
    if len(number) >= 11 and number[0] != '+':
        number = '+' + number

    try:
        normalized = phonenumbers.parse(number, str(country_code) if country_code else None)

        # now does it look plausible?
        if phonenumbers.is_possible_number(normalized):
            return phonenumbers.format_number(normalized, phonenumbers.PhoneNumberFormat.E164), True
    except Exception:
        pass

    # this must be a local number of some kind, just lowercase and save
    return regex.sub('[^0-9a-z]', '', number.lower(), regex.V0), False
예제 #21
0
def number_phone_function():
    print(" ")
    print("ATTENTION DONT FORGET => +48... <= OR SOMETHING LIKE THAT...")

    y = input("write phonenumber => ")
    x = phonenumbers.parse(y, None)
    print(x)

    x2 = phonenumbers.is_possible_number(x)
    print("is possible number? =>", x2)

    x3 = phonenumbers.is_valid_number(x)
    print("is valid number? =>", x3)

    #country..
    print("from where is use the number? =>",
          geocoder.description_for_number(x, 'pl'))

    #services..
    print("services of phonenumber? =>", carrier.name_for_number(x, 'pl'))

    #timezone..
    print("timezone =>", timezone.time_zones_for_number(x))

    print(" ")
예제 #22
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()
예제 #23
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
예제 #24
0
    def _format_phone_number(self, value, attr):
        """Format and validate a phone number."""
        strict_validation = self.get_field_value('strict_phone_validation',
                                                 default=False)
        strict_region = self.get_field_value('strict_phone_region',
                                             default=strict_validation)
        region = self.get_field_value('region', 'US')
        phone_number_format = self.get_field_value(
            'phone_number_format',
            default=phonenumbers.PhoneNumberFormat.INTERNATIONAL)

        # Remove excess special chars, except for the plus sign
        stripped_value = re.sub(r'[^\w+]', '', value)

        try:
            if not stripped_value.startswith('+') and not strict_region:
                phone = phonenumbers.parse(stripped_value, region)
            else:
                phone = phonenumbers.parse(stripped_value)

            if (not phonenumbers.is_possible_number(phone)
                    or not phonenumbers.is_valid_number(phone)
                    and strict_validation):
                raise ValidationError(
                    "The value for {} ({}) is not a valid phone "
                    "number.".format(attr, value))

            return phonenumbers.format_number(phone, phone_number_format)

        except phonenumbers.phonenumberutil.NumberParseException as exc:
            if strict_validation or strict_region:
                raise ValidationError(exc)
예제 #25
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
예제 #26
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)
예제 #27
0
def libphonenumber_parse_number(phone, country='CN'):
    phone_list = pre_process_number(phone)
    if not phone_list:
        return [('wrong', '', '')]
    new_list = []
    for phone, extension in phone_list:
        type = ''
        try:
            phone_obj = phonenumbers.parse(phone, country)
        except phonenumbers.phonenumberutil.NumberParseException:
            type = 'wrong'

        if not phonenumbers.is_possible_number(phone_obj):  # 更宽泛
            type = 'not possible'

        if not phonenumbers.is_valid_number(phone_obj):
            type = 'not valid'

        if not type:
            type = 'right'

        f_number = phonenumbers.format_number(
            phone_obj, phonenumbers.PhoneNumberFormat.E164)
        new_list.append((type, f_number, extension))
    return new_list
예제 #28
0
def validate_possible_number(value):
    parsed = phonenumbers.parse(value, "US")

    if not phonenumbers.is_possible_number(parsed):
        raise ValidationError("Contact does not appear to have "
                              "a possible US phone number: {0}"
                              "".format(value))
예제 #29
0
 def get(self):
     res = dict()
     phoneNumber = self.request.get("number")
     country = str(self.request.get("country"))
     if phoneNumber != '' and country != '':
         try:
             info = phonenumbers.parse(phoneNumber, country.upper())
             res['country_code'] = '+' + str(info.country_code)
             res['carrier'] = carrier.name_for_number(info, "en")
             res['is_valid'] = phonenumbers.is_valid_number(info)
             res['is_possible'] = phonenumbers.is_possible_number(info)
             formats = dict()
             formats['national'] = phonenumbers.format_number(
                 info, phonenumbers.PhoneNumberFormat.NATIONAL)
             formats['international'] = phonenumbers.format_number(
                 info, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
             formats['e164'] = phonenumbers.format_number(
                 info, phonenumbers.PhoneNumberFormat.E164)
             res['formats'] = formats
         except:
             res['message'] = 'error'
         self.response.headers.add_header("Access-Control-Allow-Origin",
                                          "*")
         self.response.headers['Content-Type'] = 'application/json'
         self.response.write(json.dumps(res))
     else:
         self.set_status(404)
예제 #30
0
    def validate_phone(self, attrs, source):  # deprecated, use contacts
        org = self.org
        if org.is_anon:
            raise ValidationError(
                "Cannot start flows for anonymous organizations")

        # get a channel
        channel = self.org.get_send_channel(TEL_SCHEME)

        if channel:
            # check our numbers for validity
            for tel, phone in attrs.get(source, []):
                try:
                    normalized = phonenumbers.parse(phone,
                                                    channel.country.code)
                    if not phonenumbers.is_possible_number(normalized):
                        raise ValidationError("Invalid phone number: '%s'" %
                                              phone)
                except:
                    raise ValidationError("Invalid phone number: '%s'" % phone)
        else:
            raise ValidationError(
                "You cannot start flows without at least one channel configured"
            )

        return attrs
예제 #31
0
def validate_phone_number(text):
    try:
        number = phonenumbers.parse(text, "CA")
        if not is_possible_number(number):
            raise ValidationError
    except NumberParseException:
        raise ValidationError(NumberParseException)
예제 #32
0
    def validate(self, data):
        urns = data.get("urn", [])
        phones = data.get("phone", [])
        contacts = data.get("contact", [])
        channel = data.get("channel")

        if (not urns and not phones and not contacts) or (urns and phones):  # pragma: needs cover
            raise serializers.ValidationError("Must provide either urns or phone or contact and not both")

        if not channel:
            channel = Channel.objects.filter(is_active=True, org=self.org).order_by("-last_seen").first()
            if not channel:  # pragma: no cover
                raise serializers.ValidationError("There are no channels for this organization.")
            data["channel"] = channel

        if phones:
            if self.org.is_anon:  # pragma: needs cover
                raise serializers.ValidationError("Cannot create messages for anonymous organizations")

            # check our numbers for validity
            country = channel.country
            for urn in phones:
                try:
                    tel, phone, query, display = URN.to_parts(urn)
                    normalized = phonenumbers.parse(phone, country.code)
                    if not phonenumbers.is_possible_number(normalized):  # pragma: needs cover
                        raise serializers.ValidationError("Invalid phone number: '%s'" % phone)
                except Exception:
                    raise serializers.ValidationError("Invalid phone number: '%s'" % phone)

        return data
예제 #33
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()
예제 #34
0
def number_check(numbers, country):
    
    # Preconditions
    assert type(numbers) == list
    assert type(country) == str
    
    # Empty dictionaries which will store check results
    possibility_results = dict()
    validity_results = dict()

    # Run through each number in the input list - check they are possible/valid numbers for the specified country
    for number in numbers:
    
        number_obj = phonenumbers.parse(number, country)                 # Convert number to a 'phone number object'
        
        possibility_check = phonenumbers.is_possible_number(number_obj)  # Determine if phone number object is possible
        
        possibility_results[number] = possibility_check                  # Append result of check to dictionary
    
    
        validity_check = phonenumbers.is_valid_number(number_obj)        # Determine if phone number object is valid
        
        validity_results[number] = validity_check                        # Append result of check to dictionary
        
        
    return possibility_results, validity_results
예제 #35
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
예제 #36
0
 def simple_scan(self, working=True):
     # function to get the basic info about a number (phonenumbers module)
     phone = phonenumbers.parse(self.phonenumber)
     if not phonenumbers.is_valid_number(phone):
         return False
     if phonenumbers.is_possible_number(phone):
         print(f"{b}{plus} The number is valid and possible.")
     else:
         print(f"{b}{warn} The number is valid but not possible.")
     international = phonenumbers.format_number(
         phone, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
     countrycode = phonenumbers.format_number(
         phone, phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(" ")[0]
     country = geocoder.country_name_for_number(phone, 'en')
     location = geocoder.description_for_number(phone, 'en')
     carrierr = carrier.name_for_number(phone, 'en')
     # ------------------------------------------------------------------------
     if working:
         print(f'{b}{plus} International Format : {international}')
         print(
             f'{b}{plus} Country name         : {country} ({countrycode})')
         print(f'{b}{plus} City/Province        : {location}')
         print(f'{b}{plus} Carrier              : {carrierr}')
         for time in timezone.time_zones_for_number(phone):
             print(f'{b}{plus} Timezone             : {time}')
예제 #37
0
def set_internal_user_info(pubkey, **kwargs):
    """Add optional details in local user info."""
    # Verify user exists.
    get_user(pubkey)

    user_details = get_internal_user_infos(pubkey)
    if kwargs:
        if 'phone_number' in kwargs:
            # validate and fix (if possible) phone number
            try:
                phone_number = phonenumbers.parse(kwargs['phone_number'])
                valid_number = phonenumbers.is_valid_number(phone_number)
                possible_number = phonenumbers.is_possible_number(phone_number)
                if not valid_number or not possible_number:
                    raise InvalidPhoneNumber('Invalid phone number')
                kwargs['phone_number'] = phonenumbers.format_number(
                    phone_number, phonenumbers.PhoneNumberFormat.E164)
            except phonenumbers.phonenumberutil.NumberParseException as exc:
                raise InvalidPhoneNumber("Invalid phone number. {}".format(str(exc)))

        user_details.update(kwargs)
        user_details['pubkey'] = pubkey
        if 'timestamp' in user_details:
            del user_details['timestamp']
        with SQL_CONNECTION() as sql:
            sql.execute("INSERT INTO internal_user_infos ({}) VALUES ({})".format(
                ', '.join(user_details.keys()), ', '.join(['%s' for key in user_details])
            ), (list(user_details.values())))

        # Run basic test as soon as (and every time) all basic details are filled.
        if all([user_details.get(key) for key in ['full_name', 'phone_number', 'address']]):
            update_test(pubkey, 'basic', csl_reader.CSLListChecker().basic_test(user_details['full_name']))
예제 #38
0
def isValidPhoneState(form, field):
    try:
        input_number = phonenumbers.parse(field.data, 'US')
        if not phonenumbers.is_possible_number(input_number):
            raise ValidationError('Invalid phone number.')
    except Exception as e:
        raise ValidationError(e.args)
예제 #39
0
    def extract_phone(self, field_value):
        """
        Parses the input string to create a PhoneNumber entity with all the possible
        values.

        Args:
            field_value -> The value of the field where the information will be
                collected from
        """
        try:
            parsed = phonenumbers.parse(field_value)
        except phonenumbers.NumberParseException as e:
            # The phone number couldn't be parsed
            return None

        # Checks if it could be a phone number, but not if it could be real
        if phonenumbers.is_possible_number(parsed):

            nsn = str(phonenumbers.national_significant_number(parsed))
            ndc_len = phonenumbers.length_of_national_destination_code(parsed)

            if ndc_len > 0:
                area_code = nsn[:ndc_len]
                lastnumbers = nsn[ndc_len:]
            else:
                area_code = None
                lastnumbers = nsn

            return ents.PhoneNumber(phonenumber=field_value,
                                    countrycode=parsed.country_code,
                                    areacode=area_code if area_code else None,
                                    lastnumbers=lastnumbers)

        return None
예제 #40
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
예제 #41
0
파일: data.py 프로젝트: mcmontero/tinyAPI
    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)
예제 #42
0
 def validate_phone_number(self, field):
     error_message = "Invalid phone number. Example: +5599999999"
     try:
         data = phonenumbers.parse(field.data)
     except:
         raise validators.ValidationError(error_message)
     if not phonenumbers.is_possible_number(data):
         raise validators.ValidationError(error_message)
예제 #43
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')
예제 #44
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
예제 #45
0
def generify_phone_search(search_term):
    try:
        phone_number = phonenumbers.parse(search_term.strip(), 'US')
        if phonenumbers.is_possible_number(phone_number):
            return phonenumbers.format_number(phone_number, phonenumbers.PhoneNumberFormat.NATIONAL)
    except phonenumbers.NumberParseException:
        pass

    return search_term
예제 #46
0
def parsePhoneNumber(n,debugging = False):
	if debugging: print (n)
	n = pn.parse(n,'GB')
	assert (pn.is_possible_number(n))	
	isUK = pn.is_valid_number_for_region(n,'GB')
	if debugging: print('valid UK number?',isUK)
	INTN = pn.format_number(n, pn.PhoneNumberFormat.INTERNATIONAL)
	if debugging: print INTN
	return INTN
예제 #47
0
def validate_phone(phone):
    try:
        p = phonenumbers.parse(phone, DEFAULT_REGION)
    except phonenumbers.NumberParseException:
        return False
    if not phonenumbers.is_possible_number(p):
        return False
    if not phonenumbers.is_valid_number(p):
        return False
    return True
예제 #48
0
def validate_phone(form, field):
    try:
        # parse field into PhoneNumber object
        phone = pn.parse(field.data, None)

        # if StringField is not in the correct format, raise validation error
        if not pn.is_valid_number(phone) or not pn.is_possible_number(phone):
            raise ValidationError('Field must be valid phone number')
    except pn.phonenumberutil.NumberParseException:
        raise ValidationError('Field must be valid phone number')
예제 #49
0
def phone(value, prop=None, **kwargs):
    try:
        value = string_value(value)
        if value is None:
            return
        num = phonenumbers.parse(value, prop.country)
        if phonenumbers.is_possible_number(num):
            return phonenumbers.format_number(num, phonenumbers.PhoneNumberFormat.INTERNATIONAL)  # noqa
    except Exception:
        return
예제 #50
0
def parse_phone_number(phone_number, default_country):
    try:
        number = phonenumbers.parse(phone_number, default_country)
    except phonenumbers.phonenumberutil.NumberParseException:
        return None

    if not phonenumbers.is_possible_number(number):
        return None

    return number
예제 #51
0
파일: regex.py 프로젝트: adamchainz/aleph
 def get_number(self, num, country=None):
     if country is not None:
         country = country.upper()
     try:
         num = phonenumbers.parse(num, country)
         if phonenumbers.is_possible_number(num):
             if phonenumbers.is_valid_number(num):
                 return phonenumbers.format_number(num, self.FORMAT)
         return None
     except NumberParseException:
         return None
예제 #52
0
파일: helpers.py 프로젝트: Madelena/serkli
def is_phone(phone_str):
    import phonenumbers

    try:
        z = phonenumbers.parse(phone_str, "US")

        if phonenumbers.is_possible_number(z): 
            if phonenumbers.is_valid_number(z):
                return True
    except:
        return False
예제 #53
0
def validate_phone(my_country, my_phone):
    try:
        entry = Country.objects.get(name__iexact=my_country)
        country_code = entry.code2
    except:
        print('No matching country in database')
        return "missing"
    print(country_code)
    parsed_number = phonenumbers.parse(my_phone, country_code)
    return (phonenumbers.is_valid_number(parsed_number)
            and phonenumbers.is_possible_number(parsed_number))
예제 #54
0
파일: schema.py 프로젝트: eea/eea.usersdb
def _phone_validator(node, value):
    """Check if provided number is possible number"""
    if not value:
        return
    try:
        number = phonenumbers.parse(value)
    except Exception:
        raise colander.Invalid(node, INVALID_PHONE_MESSAGES[0])
    else:
        if not phonenumbers.is_possible_number(number):
            raise colander.Invalid(node, INVALID_PHONE_MESSAGES[1])
예제 #55
0
    def phone_parse(number, country_code):
        try:
            phone_nbr = phonenumbers.parse(number, region=country_code, keep_raw_input=True)
        except phonenumbers.phonenumberutil.NumberParseException as e:
            raise UserError(_('Unable to parse %s:\n%s') % (number, e))

        if not phonenumbers.is_possible_number(phone_nbr):
            raise UserError(_('Impossible number %s: probably invalid number of digits') % number)
        if not phonenumbers.is_valid_number(phone_nbr):
            raise UserError(_('Invalid number %s: probably incorrect prefix') % number)

        return phone_nbr
예제 #56
0
    def validate_phone(self, value):
        if value:
            try:
                normalized = phonenumbers.parse(value, None)
                if not phonenumbers.is_possible_number(normalized):
                    raise serializers.ValidationError("Invalid phone number: '%s'" % value)
            except Exception:
                raise serializers.ValidationError("Invalid phone number: '%s'" % value)

            e164_number = phonenumbers.format_number(normalized, phonenumbers.PhoneNumberFormat.E164)
            self.parsed_urns = [URN.from_tel(e164_number)]
        return value
예제 #57
0
    def validate_phone(self, attrs, source):
        phone = attrs.get(source, None)
        if phone:
            try:
                normalized = phonenumbers.parse(phone, None)
                if not phonenumbers.is_possible_number(normalized):
                    raise ValidationError("Invalid phone number: '%s'" % phone)
            except:  # pragma: no cover
                raise ValidationError("Invalid phone number: '%s'" % phone)

            phone = phonenumbers.format_number(normalized, phonenumbers.PhoneNumberFormat.E164)
            attrs['phone'] = phone
        return attrs
예제 #58
0
def validate_phone_number(value):
    "Validates a phone number is a possible number and is in E164 format."

    try:
        p = phonenumbers.parse(value)
    except NumberParseException:
        raise ValidationError("{} does not appear to be a valid phone number".format(value))

    if value != phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.E164):
        raise ValidationError("{} needs to be in E164 format".format(value))

    if not phonenumbers.is_possible_number(p):
        raise ValidationError('{} does not appear to be a valid phone number'.format(value))