Example #1
0
    def check_for_country_code(self, phone_num):
        """
        :param phone_num: the number which is to be checked for country code
        :return: dict with country_code if it's in phone_num or phone_number with current country code
        Examples:
            phone_num = '919123456789'
            countryCallingCode = 'IN'
            {countryCallingCode:"91",value:"9123456789"}
        """
        phone_dict = {}

        if len(phone_num) > 10:
            check_country_regex = re.compile(r'^({country_code})\d{length}$'.
                                             format(country_code='911|1|011 91|91', length='{10}'), re.U)
            p = check_country_regex.findall(phone_num)
            if len(p) == 1:
                phone_dict['country_calling_code'] = p[0]
                country_code_sub_regex = re.compile(r'^{detected_code}'.format(detected_code=p[0]))
                phone_dict['value'] = country_code_sub_regex.sub(string=phone_num, repl='')
            else:
                phone_dict['country_calling_code'] = str(phonenumbers.country_code_for_region(self.country_code))
                phone_dict['value'] = phone_num
        else:
            phone_dict['country_calling_code'] = str(phonenumbers.country_code_for_region(self.country_code))
            phone_dict['value'] = phone_num

        return phone_dict
Example #2
0
    def generate_phone(phone, ip):
        """根据手机号和ip生成通用的可直接发送短信验证码的手机号码.

        Args:
            phone(str): 数字字符串, e.g.: 18612491222
            ip:

        Returns(str):
          符合国际标准的手机号码, e.g.: +8618612491222

        """
        assert phone.isnumeric()
        try:
            # 验证手机号码
            pn = phonenumbers.parse("+{}".format(phone))
            if phonenumbers.is_valid_number(pn):
                return "+{}".format(phone)
        except phonenumbers.NumberParseException:
            pass
        resp = reader.country(ip)
        region_code = resp.country.iso_code
        country_code = phonenumbers.country_code_for_region(region_code)
        pn = phonenumbers.parse("+{}{}".format(country_code, phone))
        if phonenumbers.is_valid_number(pn):
            return "+{}{}".format(country_code, phone)
        raise ValueError("{} is not valid phone")
Example #3
0
 def from_json(self, _json):
     value = json.loads(_json)
     self.region_code = value.get('regionCode')
     self.phone_number = value.get('phoneNumber')
     self.country_code = phonenumbers.country_code_for_region(
         self.region_code)
     return self
 def _get_prefix_from_country(self, cr, uid, context=None):
     user = self.pool['res.users'].browse(cr, uid, uid, context=context)
     country_code = user.company_id and user.company_id.partner_id and user.company_id.partner_id.country_id and user.company_id.partner_id.country_id.code or False
     default_country_prefix = False
     if country_code:
         default_country_prefix = phonenumbers.country_code_for_region(country_code)
     return default_country_prefix
Example #5
0
def parse_phone(phone_str, country_code=0, alpha2=u"US"):
    "returns a dict with phone number properties if the string is parsable"
    """
        returns dict w/: phone_str, phone_str_digits_only, country_code, region, errors (if any)
    """
    try:
        if COUNTRY_RG.match(phone_str):
            phone = parse_number(rm_punct_leaving_plus_sign(phone_str), keep_raw_input=True)
        elif country_code != 0:
            phone = parse_number(u"+{} {}".format(country_code, phone_str), keep_raw_input=True)
        else:
            country_code = country_code_for_region(alpha2)
            if country_code != 0:
                phone = parse_number(u"+{} {}".format(country_code, phone_str), keep_raw_input=True)
            else:
                phone = parse_number(phone_str, alpha2, keep_raw_input=True)
        phone_dict = phone.__dict__.copy()
        phone_dict['region_code'] = region_code_for_country_code(phone.country_code)
        phone_dict['phone_str'] = phone_str
        phone_dict['is_valid_for_region'] = is_valid_number_for_region(phone, region_code_for_country_code(phone.country_code))
    except:
        keys = ['region_code','italian_leading_zero','extension','national_number','is_valid_for_region','raw_input','country_code_source','phone_str','country_code','number_of_leading_zeros','preferred_domestic_carrier_code']
        phone_dict = {k: None for k in keys}
        phone_dict['phone_str'] = phone_str
    return phone_dict
Example #6
0
 def _get_prefix_from_country(self, cr, uid, context=None):
     user = self.pool['res.users'].browse(cr, uid, uid, context=context)
     country_code = user.company_id and user.company_id.partner_id and user.company_id.partner_id.country_id and user.company_id.partner_id.country_id.code or False
     default_country_prefix = False
     if country_code:
         default_country_prefix = phonenumbers.country_code_for_region(
             country_code)
     return default_country_prefix
Example #7
0
 def setUp(self):
     self.client = Client()
     self.user_without_permission = User.objects.create_user(
         username='******', email='*****@*****.**', password='******')
     self.raj = self.assign_permission_to(User.objects.create_user(
         'demo13', '*****@*****.**', 'demo13'), 'can_view_users')
     self.client.login(username='******', password='******')
     country_code = pycountry.countries.lookup(settings.COUNTRY).alpha_2
     self.country_phone_code = '+%s' % phonenumbers.country_code_for_region(country_code)
Example #8
0
 def setUp(self):
     self.client = Client()
     self.user_without_permission = User.objects.create_user(
         username='******', email='*****@*****.**', password='******')
     self.raj = self.assign_permission_to(
         User.objects.create_user('demo13', '*****@*****.**', 'demo13'),
         'can_view_users')
     self.client.login(username='******', password='******')
     country_code = pycountry.countries.lookup(settings.COUNTRY).alpha_2
     self.country_phone_code = '+%s' % phonenumbers.country_code_for_region(
         country_code)
    def detect_entity(self, text, **kwargs):
        """Detects phone numbers in the text string

        Args:
            text: string to extract entities from
            **kwargs: it can be used to send specific arguments in future.

        Returns:

            self.phone (list): list consisting the detected phone numbers and their country calling codes
            self.original_phone_text (list): list containing their corresponding substrings in the original message.

        Examples:

        text = 'call +1 (408) 912-6172'
        p = PhoneDetector(entity_name='phone_number', language='en', locale='en-US')
        p.detect_entity(text=text)
        ([{'country_calling_code':'1', value':'4089126172'} ],
         [u'+1 (408) 912-6172'])

        text = '+९१ ९८१९९८३१३२ पर कॉल करें और संदेश ९८२०३३४४१६ पर कॉल करें'
        p = PhoneDetector(entity_name='phone_number', language='hi', locale='en-IN')
        p.detect_entity(text=text)
        ([{'country_calling_code':'91', value':'9819983132'}
        ,{ 'country_calling_code':'91', value:'9820334416'} ],
        [u'+९१ ९८१९९८३१३२', u'+९१ ९८१९९८३१३२'])

        """
        self.text = " " + text.lower().strip() + " "
        self.phone, self.original_phone_text = [], []
        for match in phonenumbers.PhoneNumberMatcher(self.text,
                                                     self.country_code,
                                                     leniency=0):
            if match.number.country_code == phonenumbers.country_code_for_region(
                    self.country_code):
                self.phone.append(
                    self.check_for_country_code(
                        str(match.number.national_number)))
                self.original_phone_text.append(
                    self.text[match.start:match.end])
            else:
                # This means our detector has detected some other country code.
                self.phone.append({
                    "country_calling_code":
                    str(match.number.country_code),
                    "value":
                    str(match.number.national_number)
                })
                self.original_phone_text.append(
                    self.text[match.start:match.end])
        self.phone, self.original_phone_text = self.check_for_alphas()
        return self.phone, self.original_phone_text
Example #10
0
def dialing_code_for_region(phone_region: str) -> Optional[str]:
    """Gets the dialing code for the specified region.

    The dialing code is not the same as the dialing prefix.
    The dialing code is without the '+'. For example '971' for
    the UAE.

    Arguments:
        phone_region:
            Country code as defined by ISO 3166-1 alpha-2.

    Returns:
        The dialing code for the specified region.
    """
    return phonenumbers.country_code_for_region(phone_region) or None
Example #11
0
def context_extras(request):
    # basically including the country phone code in context always
    # would like to avoid this overhead in the future
    country_code = pycountry.countries.lookup(settings.COUNTRY).alpha_2
    generals = {
        'PROJECT_TITLE': settings.PROJECT_TITLE,
        'country_phone_code': '+%s' % phonenumbers.country_code_for_region(country_code),
        'cached_value': CachedValue(),
        'max_display_per_page': settings.TABLE_ENTRY_PER_PAGINATION,
        'HOME_URL': request.build_absolute_uri('/')
    }
    if request.GET:
        generals['q'] = request.GET.get('q', '')
        generals['max_display_per_page'] = request.GET.get(
            'max_display_per_page', settings.TABLE_ENTRY_PER_PAGINATION)
    return generals
Example #12
0
    def _parse(cls, value, region=None):
        # valid numbers don't start with the same digit(s) as their country code so we strip them
        country_code = phonenumbers.country_code_for_region(region)
        if country_code and value.startswith(str(country_code)):
            value = value[len(str(country_code)):]

        parsed = phonenumbers.parse(value, region)

        # strip empty extension
        if parsed.country_code == 1 and len(str(parsed.national_number)) > 10:
            regex = re.compile('.+\s*e?xt?\.?\s*$')
            if regex.match(value):
                value = re.sub('\s*e?xt?\.?\s*$', '', value)
                new_parsed = phonenumbers.parse(value, region)
                if len(str(new_parsed)) >= 10:
                    parsed = new_parsed

        return parsed
Example #13
0
    def __init__(self, *args, **kwargs):
        super(PublicSMSRateCalculatorForm, self).__init__(*args, **kwargs)

        isd_codes = []
        countries = sorted(COUNTRIES.items(), key=lambda x: x[1].encode('utf-8'))
        for country_shortcode, country_name in countries:
            country_isd_code = country_code_for_region(country_shortcode)
            isd_codes.append((country_isd_code, country_name))

        self.fields['country_code'].choices = isd_codes

        self.helper = FormHelper()
        self.helper.form_class = "form-horizontal"
        self.helper.layout = crispy.Layout(
            crispy.Field(
                'country_code',
                css_class="input-xxlarge",
                data_bind="value: country_code",
                placeholder=_("Please Select a Country Code"),
            ),
        )
Example #14
0
    def __init__(self, *args, **kwargs):
        super(PublicSMSRateCalculatorForm, self).__init__(*args, **kwargs)

        isd_codes = []
        countries = sorted(COUNTRIES.items(),
                           key=lambda x: x[1].encode('utf-8'))
        for country_shortcode, country_name in countries:
            country_isd_code = country_code_for_region(country_shortcode)
            isd_codes.append((country_isd_code, country_name))

        self.fields['country_code'].choices = isd_codes

        self.helper = FormHelper()
        self.helper.form_class = "form-horizontal"
        self.helper.layout = crispy.Layout(
            crispy.Field(
                'country_code',
                css_class="input-xxlarge",
                data_bind="value: country_code",
                placeholder=_("Please Select a Country Code"),
            ), )
def context_extras(request):
    # basically including the country phone code in context always
    # would like to avoid this overhead in the future
    country_code = pycountry.countries.lookup(settings.COUNTRY).alpha_2
    generals = {
        'PROJECT_TITLE':
        settings.PROJECT_TITLE,
        'country_phone_code':
        '+%s' % phonenumbers.country_code_for_region(country_code),
        'cached_value':
        CachedValue(),
        'max_display_per_page':
        settings.TABLE_ENTRY_PER_PAGINATION,
        'HOME_URL':
        request.build_absolute_uri('/')
    }
    if request.GET:
        generals['q'] = request.GET.get('q', '')
        generals['max_display_per_page'] = request.GET.get(
            'max_display_per_page', settings.TABLE_ENTRY_PER_PAGINATION)
    return generals
Example #16
0
def code(country):
    country = country_converter.convert(country, to="ISO2")
    if country == "not found":
        return jsonify({"message": "Resource not found"}), 404
    return jsonify({"code": phonenumbers.country_code_for_region(country)})
Example #17
0
def getSMS():
    # print(e3.get())
    I_list = []
    for c in pycountry.countries:
        I_list.append((c.alpha_2, pn.country_code_for_region(c.alpha_2)))
    newWindowPhone(I_list)
Example #18
0
 def code_generate(self):
     country_code_list = {c.alpha_2: pn.country_code_for_region(c.alpha_2) for c in pycountry.countries}
     for country_name, value in country_code_list.items():
         prefix_number = "+" + str(value)
         if not self.search([("name", "=", country_name), ("prefix_number", "=", prefix_number)]):
             self.create({"name": country_name, "prefix_number": prefix_number})
Example #19
0
 def _get_e164_numerify_pattern(self, region_code: str, is_possible=True):
     if not is_possible:
         return '#!!!!!!'
     country_code = phonenumbers.country_code_for_region(region_code)
     return str(country_code
                ) + self._e164_numerify_pattern[len(str(country_code)):]
 def from_json(self, _json):
     value = json.loads(_json)
     self.region_code = value.get('regionCode')
     self.phone_number = value.get('phoneNumber')
     self.country_code = phonenumbers.country_code_for_region(self.region_code)
     return self