Ejemplo n.º 1
0
 def save(self, *args, **kwargs):
     if self.phone_work:
         self.phone_work = phonenumbers.format_number(phonenumbers.parse(self.phone_work, 'US'), phonenumbers.PhoneNumberFormat.E164)
     if self.phone_mobile:
         self.phone_mobile = phonenumbers.format_number(phonenumbers.parse(self.phone_mobile, 'US'), phonenumbers.PhoneNumberFormat.E164)
     self.email = self.email.lower()
     super(Person, self).save(*args, **kwargs)
Ejemplo n.º 2
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.º 3
0
    def __init__(self, raw_number, country_code=None):
        # Bail if phonenumbers is not found.
        if phonenumbers is None:
            raise ImproperlyConfigured(
                "'phonenumbers' is required to use 'PhoneNumber'")

        self._phone_number = phonenumbers.parse(raw_number, country_code)
        super(PhoneNumber, self).__init__(
            country_code=self._phone_number.country_code,
            national_number=self._phone_number.national_number,
            extension=self._phone_number.extension,
            italian_leading_zero=self._phone_number.italian_leading_zero,
            raw_input=self._phone_number.raw_input,
            country_code_source=self._phone_number.country_code_source,
            preferred_domestic_carrier_code=(
                self._phone_number.preferred_domestic_carrier_code
            )
        )
        self.national = phonenumbers.format_number(
            self._phone_number,
            phonenumbers.PhoneNumberFormat.NATIONAL
        )
        self.international = phonenumbers.format_number(
            self._phone_number,
            phonenumbers.PhoneNumberFormat.INTERNATIONAL
        )
        self.e164 = phonenumbers.format_number(
            self._phone_number,
            phonenumbers.PhoneNumberFormat.E164
        )
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.º 5
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.º 6
0
 def _format(vals):
     if isinstance(vals, unicode) and vals.startswith('xxx'):
         return {
             'e164': vals,
             'international': vals,
             'rfc3966': vals,
         }
         
     pn = bss_phonenumbers_converter._parse(vals)
     if not pn:          
         return {
             'e164': None,
             'international': None,
             'rfc3966': None,
         }   
     res = {
         'e164': phonenumbers.format_number(pn, phonenumbers.PhoneNumberFormat.E164),
         'international': phonenumbers.format_number(pn, phonenumbers.PhoneNumberFormat.INTERNATIONAL),
         'rfc3966': phonenumbers.format_number(pn, phonenumbers.PhoneNumberFormat.RFC3966),
     }
     
     # Format +32XXXXXXXXX Belgian numbers according to test in portal_crm (which will succeed with this format) : 
     if res['e164'][:3] == '+32' and len(res['e164']) == 12:
         res['international'] = '%s %s %s %s %s' % (res['e164'][:3], res['e164'][3:6], res['e164'][6:8], 
                                                    res['e164'][8:10], res['e164'][10:12])
     return res
Ejemplo n.º 7
0
def validatePhoneNumber(number):
    valid = False

    try:
        # Leave shortcodes alone.

        if number is not None:
            if len(number) in (3, 4, 5, 6) and number.isdigit():
                return True

            # it's okay to search for the region US for all US/Can b/c they share
            # the same parsing/formatting rules
            p = phonenumbers.parse(number, 'US')

            # but we need to check the number is valid in either country
            if phonenumbers.is_valid_number_for_region(p, 'US') or \
                    phonenumbers.is_valid_number_for_region(p, 'CA'):
                phonenumbers.format_number(
                    p,
                    phonenumbers.PhoneNumberFormat.E164
                )
                valid = True
    except phonenumbers.NumberParseException as e:
        logging.error('Detected invalid phone number: {0}-{1}'.format(
            number, e))
    return valid
Ejemplo n.º 8
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.º 9
0
    def render_POST(self, request):
        send_cors(request)

        error, args = get_args(request, ('phone_number', 'country', 'client_secret', 'send_attempt'))
        if error:
            request.setResponseCode(400)
            return error

        raw_phone_number = args['phone_number']
        country = args['country']
        clientSecret = args['client_secret']
        sendAttempt = args['send_attempt']

        try:
            phone_number_object = phonenumbers.parse(raw_phone_number, country)
        except Exception as e:
            logger.warn("Invalid phone number given: %r", e)
            request.setResponseCode(400)
            return {'errcode': 'M_INVALID_PHONE_NUMBER', 'error': "Invalid phone number" }

        msisdn = phonenumbers.format_number(
            phone_number_object, phonenumbers.PhoneNumberFormat.E164
        )[1:]

        # International formatted number. The same as an E164 but with spaces
        # in appropriate places to make it nicer for the humans.
        intl_fmt = phonenumbers.format_number(
            phone_number_object, phonenumbers.PhoneNumberFormat.INTERNATIONAL
        )

        resp = None

        try:
            sid = self.sydent.validators.msisdn.requestToken(
                phone_number_object, clientSecret, sendAttempt, None
            )
        except DestinationRejectedException:
            logger.error("Destination rejected for number: %s", msisdn);
            request.setResponseCode(400)
            resp = {'errcode': 'M_DESTINATION_REJECTED', 'error': 'Phone numbers in this country are not currently supported'}
        except Exception as e:
            logger.error("Exception sending SMS: %r", e);
            request.setResponseCode(500)
            resp = {'errcode': 'M_UNKNOWN', 'error':'Internal Server Error'}

        if not resp:
            resp = {
                'success': True, 'sid': str(sid),
                'msisdn': msisdn, 'intl_fmt': intl_fmt,
            }

        return resp
Ejemplo n.º 10
0
def format_for_display(value, region):
    try:
        phonenumber = phonenumbers.parse(value, region)
    except phonenumbers.NumberParseException:
        # For historical data that may not be parseable
        return value

    if phonenumbers.is_valid_number_for_region(phonenumber, region):
        return phonenumbers.format_number(
            phonenumber, phonenumbers.PhoneNumberFormat.NATIONAL)
    else:
        return phonenumbers.format_number(
            phonenumber, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
Ejemplo n.º 11
0
def _format_phonenumber(phonenumber_obj, case=1):
    if case == 1:
        return phonenumbers.format_number(
                    phonenumber_obj,
                    phonenumbers.PhoneNumberFormat.E164)
    elif case == 2:
        return phonenumbers.format_number(
                    phonenumber_obj,
                    phonenumbers.PhoneNumberFormat.NATIONAL).replace(' ', '')
    elif case == 3:
        return phonenumbers.format_number(
                    phonenumber_obj,
                    phonenumbers.PhoneNumberFormat.mro).replace(' ', '')
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'
def clean_phone_number(phone_number):
    # Takes a phone number and returns a parsed copy conforming to the international schema ("+00 00 0000-0000").

    import phonenumbers #importing phonenumbers module

    #defining list of problematic numbers mapped in the audit phase
    prob_phone = ["55 11 3884 4016 / 97680-0017", "+11 55 4356 5226", "+55 11 1 3135 4156","+55 11 11 2063 9494","+55 11 2901-3155 / 2769-2901","+55 11 3814-3819  -  3031-1065","+55 11 433 .7185","+55 11+55 11","+55 11193","+55 11190","+55 4104 3859","+55 4109 2485","+55 4343 6454","11 2959-3594 / 2977-2491","11 3091-3503 / 3091-3596","3862-2772 / 36730360","55+ (11) 3670-8000","+55 11 11 4128 2828","+55 11 11 4392 6611"]

    #treating phone numbers to be parsed later
    if ("-" not in phone_number) and (len(phone_number) <= 9) or (" " not in phone_number) and (len(phone_number) <= 9):
        phone_number = "+55 11" + phone_number

    elif ("-" in phone_number) and (len(phone_number) <= 10) or (" " not in phone_number) and (len(phone_number) <= 10):
        phone_number = "+55 11" + phone_number

    elif phone_number in prob_phone:
        prob_phone_mapping = { "+11 55 4356 5226": "+55 11 4356 5226",
                "+55 11 1 3135 4156": "+55 11 3135 4156",
                "+55 11 11 2063 9494": "+55 11 2063 9494",
                "+55 11 11 4128 2828": "+55 11 4128 2828",
                "+55 11 11 4392 6611": "+55 11 4392 6611",
                "+55 11 2901-3155 / 2769-2901": "+55 11 2901-3155 / +55 11 2769-2901",
                "+55 11 3814-3819  -  3031-1065": "+55 11 3814-3819  -  +55 11 3031-1065",
                "+55 11 433 .7185": "+55 11 43337185",
                "+55 11+55 11": "+55 11",
                "+55 11193": "+55 11",
                "+55 11190": "+55 11",
                "+55 4104 3859": "+55 11 4104 3859",
                "+55 4109 2485": "+55 11 4109 2485",
                "+55 4343 6454": "+55 11 4343 6454",
                "11 2959-3594 / 2977-2491": "11 2959-3594 / 11 2977-2491",
                "11 3091-3503 / 3091-3596": "11 3091-3503 / 11 3091-3596",
                "3862-2772 / 36730360": "11 3862-2772 / 11 36730360",
                "55+ (11) 3670-8000": "+55 (11) 3670-8000",
                "55 11 3884 4016 / 97680-0017": "55 11 3884 4016 / 11 97680-0017"}

        for item in prob_phone_mapping.iteritems():
                if phone_number == item[0]:
                    phone_number = item[1]

    #parsing phone numbers using functions from the phonenumbers module
    try:
        x = phonenumbers.parse(phone_number, "BR")
        parsed_phone_number = phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
    except:
        parsed_phone_number = []
        for match in phonenumbers.PhoneNumberMatcher(phone_number, "BR"):
            parsed_phone = phonenumbers.format_number(match.number, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
            parsed_phone_number.append(parsed_phone) #if the original string contains more than a number, they are converted into a list.

    return parsed_phone_number
Ejemplo n.º 14
0
def get_normalized_phone_review(me):
    try:
        if 'phones' in me.keys():
            if len(me['phones']):
                if len(me['phones']) > 1:
                    return( phonenumbers.format_number(phonenumbers.parse(me['phones'][0], 'US'), phonenumbers.PhoneNumberFormat.NATIONAL))
                else:
                    return( phonenumbers.format_number(phonenumbers.parse(me['phones'][0], 'US'), phonenumbers.PhoneNumberFormat.NATIONAL))
            else:
                return np.nan
        else:
            return np.nan
    except:
        return np.nan
Ejemplo n.º 15
0
    def display_phone(self, field_name=None, phone=None, country='BE', check=True, format='', pattern=''):
        """
            Return a formatted localized phone number.
            country = 2 letters country code
            check = check the validity of the given phone
            format = 'nat' or 'int'
            pattern = space replacing separators in rtl order
                      * list of 2 lists for nat and int formats => [['/', '.'], ['-', '.']]
                      * string or 2 strings (pipe separator) for nat and int formats '/.|-.'
        """
        if field_name:
            phone = self.get_value(field_name)
        if not phone:
            return u''
        try:
            number = phonenumbers.parse(phone, country)
        except phonenumbers.NumberParseException:
            return translate(u"Bad phone number: '${nb}'", domain='collective.documentgenerator',
                             mapping={'nb': phone}, context=self.request)
            return safe_unicode(phone)
        if check and not phonenumbers.is_valid_number(number):
            return translate(u"Invalid phone number: '${nb}'", domain='collective.documentgenerator',
                             mapping={'nb': phone}, context=self.request)

        def format_with_pattern(nb):
            if not pattern:
                return nb
            index = 0
            if nb.startswith('+'):
                index = 1
            if isinstance(pattern, list):
                pat = len(pattern) > index and pattern[index] or ''
            else:
                lst = pattern.split('|')
                pat = len(lst) > index and lst[index] or ''
            if not pat:
                return nb
            nbl = []
            for i, part in enumerate(nb.split()):
                nbl.append(part)
                nbl.append((pat[i:i + 1] + pat[-1:])[0])
            return ''.join(nbl[:-1])
        if format:
            ret = format_with_pattern(phonenumbers.format_number(number, format == 'int' and 1 or 2))
        elif country in phonenumbers.data._COUNTRY_CODE_TO_REGION_CODE.get(number.country_code, []):
            ret = format_with_pattern(phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.NATIONAL))
        else:
            ret = format_with_pattern(phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.INTERNATIONAL))
        return ret
Ejemplo n.º 16
0
def StdPhone(stringa, country):
    if gL.trace: gL.log(gL.DEBUG)   
    try:
        
        test = stringa.split(' - ')   # due numeri di tel separati da trattino
        if len(test) > 1:
            stringa = test[0]
    
        ISO = gL.CountryISO.get(country) 
        if ISO is None:
            gL.cMySql.execute("select CountryIso2 from T_Country where Country = %s", ([country]))
            row = gL.cMySql.fetchone()
            if row:
                ISO = row['CountryIso2']           
                gL.CountryISO[country] = ISO

        if ISO is None:
            gL.log(gL.ERROR, "Lingua non trovata")
            return False
    except:
        gL.log(gL.ERROR, stringa)
        gL.log(gL.ERROR, err)
        return False, False
    
    # formatta telefono
    try:
        newphone = '' ; newphone1 = '' ; idx = 0
        numeri = phonenumbers.PhoneNumberMatcher(stringa, ISO)
        while numeri.has_next():
            idx = idx + 1
            match = numeri.next()
            #print(phonenumbers.format_number(b.number, phonenumbers.PhoneNumberFormat.INTERNATIONAL))
            if idx == 1:
                newphone = phonenumbers.format_number(match.number, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
                newphone = newphone.replace('(','')
                newphone = newphone.replace(')','')
            if idx == 2:
                #match = phonenumbers.parse(stringa, ISO)
                newphone1 = phonenumbers.format_number(match.number, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
                #newphone = phonenumbers.format_number(y, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
                newphone1 = newphone1.replace('(','')
                newphone1 = newphone1.replace(')','')    
    except:
        msg ="%s - %s" % ("Phone stdz error", stringa)
        gL.log(gL.ERROR, msg)
        newphone = stringa
        return False, False
    
    return (newphone, newphone1)
Ejemplo n.º 17
0
 def generic_phonenumber_to_e164(
         self, cr, uid, ids, field_from_to_seq, context=None):
     result = {}
     from_field_seq = [item[0] for item in field_from_to_seq]
     for record in self.read(cr, uid, ids, from_field_seq, context=context):
         result[record['id']] = {}
         for fromfield, tofield in field_from_to_seq:
             if not record.get(fromfield):
                 res = False
             else:
                 try:
                     res = phonenumbers.format_number(
                         phonenumbers.parse(record.get(fromfield), None),
                         phonenumbers.PhoneNumberFormat.E164)
                 except Exception, e:
                     _logger.error(
                         "Cannot reformat the phone number '%s' to E.164 "
                         "format. Error message: %s"
                         % (record.get(fromfield), e))
                     _logger.error(
                         "You should fix this number and run the wizard "
                         "'Reformat all phone numbers' from the menu "
                         "Settings > Configuration > Phones")
                 # If I raise an exception here, it won't be possible to
                 # install the module on a DB with bad phone numbers
                     res = False
             result[record['id']][tofield] = res
Ejemplo n.º 18
0
    def run(self, **kwargs):
        global contacts
        global allgroups

        user = User.objects.get(email='*****@*****.**')
        contacts = []
        allgroups = []
        #print "sync google contacts"
        admin_accounts = GoogleAdminAccounts.objects.filter(enable=True).order_by('priority').reverse()
        if len(admin_accounts) > 0 :
            account = admin_accounts[0]
            gather_contacts(account.email, account.password)
            write_contacts()
            for contact in contacts:
                t = timezone.now() # offset-awared datetime
                now_aware = contact['last_changed'].replace(tzinfo=pytz.UTC)
                #t.astimezone(timezone.utc).replace(tzinfo=None)
                #print now_aware < account.last_changed
                if len(contact['phones']) > 0 :
                    p = PhoneNumber()
                    p.user = user
                    pn = phonenumbers.format_number(contact['phones'][0]['tel'], phonenumbers.PhoneNumberFormat.E164)
                    found_type = ""
                    for tel_type in tel_types:
                        if tel_type in contact['phones'][0]['type'] :
                            found_type = tel_type

                    #found = any(contact['phones'][0]['type'] in item for item in tel_types)
                    print 'fnd:', found_type
                    p.phone_type = found_type
                    p.phone_number = pn
                    p.save()
            account.last_changed = t
            account.save()
Ejemplo n.º 19
0
def normalize_phone(value):
    """
    Normalize a phone number to E.164 format.

    Return None if the given value can't be parsed as a phone number.

    """
    if not value:
        return None

    if value[0] == '+':
        # Phone number may already be in E.164 format.
        parse_type = None
    else:
        # Assume US format otherwise
        parse_type = 'US'
    try:
        phone_representation = phonenumbers.parse(value, parse_type)
    except phonenumbers.NumberParseException:
        return None
    else:
        formatted = phonenumbers.format_number(
            phone_representation, phonenumbers.PhoneNumberFormat.E164)

    # we only accept US/Canada numbers, they must be twelve digits in E.164
    if len(formatted) != 12:
        return None

    return formatted
Ejemplo n.º 20
0
 def generate_fake(count=100):
     from random import choice, randint
     from faker import Faker
     from .user import User
     import phonenumbers
     nusers = User.objects().count()
     fake = Faker()
     # fake.seed(3123)
     fake_pods = []
     for i in range(count):
         if nusers > 0:
             user = User.objects()[randint(0, nusers - 1)]
         else:
             user = User.generate_fake(1)[0]
         pod = Pod(
             name=fake.first_name() + '-' + fake.last_name() + '-' +
             str(fake.random_int(min=1000)),
             owner=user,
             pod_id=fake.random_int(min=20),
             qr='https://s3.amazonaws.com/pulsepodqrsvgs/default.svg',
             imei=str(randint(100000000000000, 999999999999999)),
             radio='gsm',
             mode=choice(['normal', 'teenager', 'asleep', 'inactive']),
             number=phonenumbers.format_number(
                 phonenumbers.parse(
                     '1' + ''.join([str(randint(0, 9)) for x in range(7)]),
                     'US'),
                 phonenumbers.PhoneNumberFormat.E164),
         )
         try:
             pod.save()
             fake_pods.append(pod)
         except:
             "Pod save failed"
     return fake_pods
Ejemplo n.º 21
0
def phoneformat(phone_number, phone_format='INTERNATIONAL'):
    try:
        parsed_number = parse(phone_number, None)
        format = getattr(PhoneNumberFormat, phone_format)
        return format_number(parsed_number, format)
    except NumberParseException:
        return phone_number
Ejemplo n.º 22
0
def format(self, text, oldtag=None, phone=False, phone_format="international"):
    if self.pool.get("base.phone.installed") and phone and text:
        # text should already be in E164 format, so we don't have
        # to give a country code to phonenumbers.parse()
        phone_number = phonenumbers.parse(text)
        if phone_format == "international":
            res = phonenumbers.format_number(phone_number, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
        elif phone_format == "national":
            res = phonenumbers.format_number(phone_number, phonenumbers.PhoneNumberFormat.NATIONAL)
        elif phone_format == "e164":
            res = phonenumbers.format_number(phone_number, phonenumbers.PhoneNumberFormat.E164)
        else:
            res = text
    else:
        res = format_original(self, text, oldtag=oldtag)
    return res
Ejemplo n.º 23
0
    def get_international_phone_number(self):
        phone_number = self._parse_phone_number()

        if phone_number is None:
            return None

        return phonenumbers.format_number(phone_number, phonenumbers.PhoneNumberFormat.E164)
Ejemplo n.º 24
0
 def validate_phone(self, value, context=None):
     try:
         number = phonenumbers.parse(value, None)
         phone_format = phonenumbers.PhoneNumberFormat.INTERNATIONAL
         return phonenumbers.format_number(number, phone_format)
     except Exception as exc:
         raise ValidationError(exc.message)
Ejemplo n.º 25
0
 def get_phone(cls, bot):
     """ Get a standardized phone number """
     try:
         x = phonenumbers.parse(bot.phone_number, "US")    
         return phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
     except:
         return "None"
Ejemplo n.º 26
0
def send_sms_twilio(phone, message, sender_phone=None):
    """
    Twilio does not support setting a source number, so the "sender_phone"
    argument is ignored
    """
    if not isinstance(phone, phonenumbers.phonenumber.PhoneNumber):
        raise ValueError('phone must be a PhoneNumber object')

    account = settings.TWILIO_CREDENTIALS['account']
    token = settings.TWILIO_CREDENTIALS['auth_token']
    from_phone_numbers = settings.TWILIO_CREDENTIALS['phone_numbers']

    # Sending is done from a random number
    chosen_from_phone_number = random.choice(from_phone_numbers)

    phone_e164 = phonenumbers.format_number(phone, phonenumbers.PhoneNumberFormat.E164)

    def log_error(message):
        # TODO Better logging ...
        print message

    client = TwilioRestClient(account, token)
    try:
        client.messages.create(
                to=phone_e164,
                from_=chosen_from_phone_number,
                body=message)
    except TwilioException as e:
        log_error(unicode(e))
        return
Ejemplo n.º 27
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
Ejemplo n.º 28
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.º 29
0
    def __build_phone(self, param):
        # XXX TOFIX
        _vcard_types = {
            'text': 'other',
            'voice': 'other',
            'fax': 'fax',
            'cell': 'mobile',
            'video': 'other',
            'pager': 'pager',
            'textphone': 'other',
        }

        phone = NewPhone()
        phone.number = param.value
        if 'TYPE' in param.params and param.params['TYPE']:
            phone_type = param.params['TYPE'][0].lower()
            if phone_type in _vcard_types:
                phone.type = _vcard_types[phone_type]
            else:
                phone.type = 'other'
        if 'PREF' in param.params:
            phone.is_primary = True
        try:
            number = phonenumbers.parse(phone.number, None)
            phone_format = phonenumbers.PhoneNumberFormat.INTERNATIONAL
            normalized = phonenumbers.format_number(number, phone_format)
            if normalized:
                phone.normalized_number = normalized
        except:
            pass
        return phone
Ejemplo n.º 30
0
def create(request):
	form = AppointmentForm()
	if request.POST:
		form = AppointmentForm(request.POST)
		if form.is_valid():
			phone_representation = phonenumbers.parse(form.cleaned_data['phone_number'], "US")
			phone_formatted = str(phonenumbers.format_number(phone_representation, phonenumbers.PhoneNumberFormat.E164))
			# get phone owner (or create then)
			patient = Patient.objects.get_or_create(phone_number=phone_formatted)[0]
			
			# make sure appointment date is in the future
			now = datetime.utcnow().replace(tzinfo=utc)
			app_date = form.cleaned_data['date']
			if now < app_date:
				appointment = Appointment(
					owner=patient,
					date = app_date,
					)
				appointment.save()
				patient.send_sms('You added an appointment!')
				return HttpResponseRedirect(reverse(detail, kwargs={
					'appointment_id':appointment.id,
					}))
	return render_to_response('appointments/create.html',{
		'form':form,
		},context_instance=RequestContext(request))
Ejemplo n.º 31
0
def handle_put_post(http_server, database_manager, session, account):
    subscription_plan_template = SubscriptionPlan(database_manager)
    subscription_conditions = [{
        "column": "is_active",
        "equivalence": "=",
        "value": 1
    }]
    subscription_plans = database_manager.fetch_by(subscription_plan_template,
                                                   subscription_conditions)
    billing_profiles = []
    for available_subscription_plan in subscription_plans:
        billing_profiles.append({
            "slug":
            available_subscription_plan.name,
            "name":
            available_subscription_plan.name.title(),
            "amount":
            available_subscription_plan.amount,
            "currency":
            available_subscription_plan.currency,
            "allowed_requests_per_month":
            available_subscription_plan.allowed_requests_per_month,
            "allowed_requests_per_month_printed":
            "{:,}".format(
                available_subscription_plan.allowed_requests_per_month),
        })
    template = fetch_template("account/register.jinja.htm")
    keys = {
        "current_page": "register",
        "billing_profiles": billing_profiles,
    }

    errors = []
    required_keys = [
        "billing_id",
        "email",
        "password",
        "verify_password",
        "phone",
        #"g-recaptcha-response"
    ]
    post_params = http_server.get_post_parameters()
    if "billing_id" in post_params:
        if post_params["billing_id"] != "free":
            required_keys += ["stripe_token"]

    keys["response"] = post_params

    for required_key in required_keys:
        if required_key not in post_params or post_params[required_key] == "":
            errors.append(required_key)

    if len(errors) == 0:
        email = post_params["email"]
        password = post_params["password"]
        verify_password = post_params["verify_password"]
        phone = post_params["phone"]
        formatted_number = phone
        if password != verify_password:
            errors.append("verify_password")
        #try:
        phone_details = phonenumbers.parse(phone, "US")
        if phonenumbers.is_valid_number(phone_details) is False:
            errors.append("phone")
        else:
            formatted_number = "+{} {}".format(
                phone_details.country_code,
                phonenumbers.format_number(
                    phone_details, phonenumbers.PhoneNumberFormat.NATIONAL))
            client = Client(settings["twilio"]["account_sid"],
                            settings["twilio"]["auth_token"])
            twilio_phone_details = client.lookups.phone_numbers(
                formatted_number).fetch(type='carrier')
            if twilio_phone_details.carrier["error_code"] is not None:
                errors.append("phone")
            else:
                if twilio_phone_details.carrier["type"] == "voip":
                    errors.append("phone_voip")
        #except:
        #    errors.append("phone")
        if validate_email(email) is False:
            errors.append("email")
        else:
            subscription_plan_name = post_params["billing_id"]
            subscription_plan = SubscriptionPlan.fetch_by_name(
                database_manager, subscription_plan_name)
            if subscription_plan is None:
                errors.append("billing_id")

    keys["errors"] = errors
    for error in errors:
        keys["error_{}".format(error)] = True

    if len(errors) > 0:
        output = template.render(keys)
        # http_server.set_status(400)
        http_server.print_headers()
        print(output)

    else:
        is_captcha_valid = True
        '''
        recaptcha_response = post_params['g-recaptcha-response']
        captcha_data = {
            "secret": settings["google_recaptcha3"]["secret_key"],
            "response": recaptcha_response
        }
        recaptcha_response = requests.post(
            settings["google_recaptcha3"],
            data=captcha_data
        )
        recapcha_json = recaptcha_response.json()

        is_captcha_valid = True
        if recapcha_json['success']:
            is_captcha_valid = True
        else:
            is_captcha_valid = False
        '''

        if is_captcha_valid is False:
            keys["error_invalid_captcha"] = True
            output = template.render(keys)
            # http_server.set_status(400)
            http_server.print_headers()
            print(output)
        else:
            is_marketing_ok = False
            if "subscribe" in post_params:
                if int(post_params["subscribe"]) == 1:
                    is_marketing_ok = True
                    keys["is_marketing_ok"] = True

            do_continue = True
            stripe_source_token = None
            stripe_customer_id = None
            stripe_subscription_id = None
            if subscription_plan.amount > 0:
                stripe.api_key = settings["stripe"]["secret_key"]

                discount_code = None
                stripe_coupon = None
                stripe_coupon_id = None
                if "discount_code" in post_params:
                    discount_code = post_params["discount_code"]
                    try:
                        stripe_coupon = stripe.Coupon.retrieve(discount_code)
                        do_continue = True
                        stripe_coupon_id = stripe_coupon.id
                    except Exception:
                        errors += ["discount_code"]
                        keys["errors"] = errors
                        for error in errors:
                            keys["error_{}".format(error)] = True
                        output = template.render(keys)
                        # http_server.set_status(400)
                        http_server.print_headers()
                        print(output)

                if do_continue is True:
                    stripe_plan = stripe.Plan.retrieve(
                        subscription_plan.stripe_id)
                    # How to acquire stripe tokens
                    # https://stripe.com/docs/sources/cards
                    # if "stripe_token" not in post_params:
                    #    raise ApiParamMissingStripeTokenError
                    stripe_source_token = post_params["stripe_token"]

                    stripe_customer_description = email
                    try:
                        customer = stripe.Customer.create(
                            description=stripe_customer_description,
                            source=stripe_source_token)
                        stripe_customer_id = customer.id

                        # will throw an exception if it fails. Must catch
                        subscription = stripe.Subscription.create(
                            customer=stripe_customer_id,
                            items=[{
                                "plan": stripe_plan.id
                            }],
                            coupon=stripe_coupon_id)
                        stripe_subscription_id = subscription.id
                    except Exception:
                        errors += ["duplicate_submission"]
                        keys["errors"] = errors
                        for error in errors:
                            keys["error_{}".format(error)] = True
                        output = template.render(keys)
                        # http_server.set_status(400)
                        http_server.print_headers()
                        print(output)
                        do_continue = False

            if do_continue is True:
                # verify email doesn't already exist
                account = Account.fetch_by_email(database_manager, email)
                if account is not None:
                    errors += ["email_taken"]
                    keys["errors"] = errors
                    for error in errors:
                        keys["error_{}".format(error)] = True
                    output = template.render(keys)
                    # http_server.set_status(400)
                    http_server.print_headers()
                    print(output)
                else:
                    registration = AccountRegistration.fetch_by_email(
                        database_manager, email)
                    if registration is not None:
                        errors += ["email_taken"]
                        keys["errors"] = errors
                        for error in errors:
                            keys["error_{}".format(error)] = True
                        output = template.render(keys)
                        # http_server.set_status(400)
                        http_server.print_headers()
                        print(output)
                    else:
                        registration_epoch = datetime.now()
                        registration = AccountRegistration(database_manager)
                        registration.email = post_params["email"]
                        registration.password = post_params["password"]
                        registration.phone = formatted_number
                        registration.subscription_plan_id = subscription_plan.id
                        registration.is_marketing_ok = is_marketing_ok
                        registration.stripe_source_id = stripe_source_token
                        registration.stripe_customer_id = stripe_customer_id
                        registration.stripe_subscription_id = stripe_subscription_id
                        registration.billing_interval = "monthly"
                        registration.billing_year = registration_epoch.year
                        registration.billing_month = registration_epoch.month
                        registration.billing_day = registration_epoch.day

                        confirmation_code = registration.generate_confirmation_code(
                        )
                        # send confirmation email
                        courier = Courier(settings["sendgrid"])
                        from_email = settings["email"]["from"]["email"]
                        subject = "Confirm your account"
                        template_id = "d-46d40e8316ba439095fdefb20b171a3e"
                        substitutions = {"confirm_code": confirmation_code}
                        response = courier.send_template_email(
                            email, from_email, subject, template_id,
                            substitutions)
                        if response.status_code != 202:
                            errors += ["email_delivery"]
                            keys["errors"] = errors
                            for error in errors:
                                keys["error_{}".format(error)] = True
                            output = template.render(keys)
                            # http_server.set_status(400)
                            http_server.print_headers()
                            print(output)
                        else:
                            registration.insert()
                            template = fetch_template(
                                "account/register-success.jinja.htm")
                            keys["email"] = post_params["email"]
                            http_server.set_status(200)
                            http_server.print_headers()
                            output = template.render(keys)
                            print(output)
 def get_full_phone_number(phone_raw, phone_country_code):
     parse_phone_number = phonenumbers.parse(phone_raw, phone_country_code)
     return phonenumbers.format_number(parse_phone_number,
                                       phonenumbers.PhoneNumberFormat.E164)
    def attempt_creation(self):
        """Validate fields and attempt to create account"""
        self.create_account_button.disabled = True

        # list of all problems with user input
        errors = []

        # the following series of conditionals are all for validating
        # user input before we attempt to insert it into the database

        if not self.username_field.text:
            errors.append('username is required')

        # neither of these should be possible (field is filtered),
        # but just in case
        elif len(self.username_field.text) > 32:
            errors.append('username maximum length is 32 characters')
        elif re.search(r'\W', self.username_field.text):
            errors.append(
                'username can only contain letters, numbers, and underscores')

        if not self.password_field.text:
            errors.append('password is required')
        elif len(self.password_field.text) < 8:
            errors.append('password minimum length is 8 characters')

        if not self.phone_field.text:
            errors.append('phone number is required')
        else:
            try:
                phone = parse_number(self.phone_field.text, 'US')
            except NumberParseException:
                valid = False
            else:
                valid = is_valid_number(phone)

            if not valid:
                errors.append(
                    f'"{self.phone_field.text}" is not a valid US phone number'
                )

        # if all inputs are valid, attempt to create a new account
        if not errors:
            try:
                create_user(self.username_field.text, self.password_field.text,
                            format_number(phone, 'NATIONAL'))
            except AccountError as e:
                # username already exists
                errors.append(e.message)
            else:
                # account created successfully
                AlertPopup(title='Success',
                           label=f'User "{self.username_field.text}" '
                           'has been created',
                           button='Go to Login',
                           on_dismiss=self.switch_to_login).open()
                return

        # display input errors to the user
        popup = AlertPopup(title='Errors',
                           label='\n'.join(f'\u2022 {e}' for e in errors),
                           button='Dismiss')
        popup.label.halign = 'left'
        popup.open()

        self.create_account_button.disabled = False
Ejemplo n.º 34
0
def normalize_phone_number(num):
    return format_number(parse(num.decode('utf-8'), 'US'),
                         PhoneNumberFormat.INTERNATIONAL)
Ejemplo n.º 35
0
 def formatted_phone(self):
     if self.phone:
         return phonenumbers.format_number(
             self.phone, phonenumbers.PhoneNumberFormat.NATIONAL)
Ejemplo n.º 36
0
 def get_NationalFormat(self):
     return phonenumbers.format_number(
         self.phonenumber_object, phonenumbers.PhoneNumberFormat.NATIONAL)
Ejemplo n.º 37
0
        first_name = ""
        last_name = ""
        if (m != None):
            first_name = m.group('FIRST_NAME')
            last_name = m.group('LAST_NAME')

        extract = phoneNumberArray.split('\n')
        website = ""
        phoneNumber = extract[0]
        if (len(extract) >= 2):
            website = extract[1]
            website = website[5:len(website)]
        phoneNumber = re.sub('[^0-9]+', '', phoneNumber)
        if (len(phoneNumber) >= 5 and len(phoneNumber) < 12):
            phoneNumber = phonenumbers.format_number(
                phonenumbers.parse(phoneNumber, 'US'),
                phonenumbers.PhoneNumberFormat.NATIONAL)
            phoneNumber = '+1' + phoneNumber[1:len(phoneNumber)]

        if (')' in phoneNumber):
            phoneNumber = re.sub('[^0-9]+', '', phoneNumber)
            phoneNumber = '+' + phoneNumber

        places = GeoText(address)
        city = places.cities
        place = ""
        if (city != []):
            place = city[0]

        pincode = ""
        # reg = re.compile('^.*(?P<zipcode>\d{6}).*$')
Ejemplo n.º 38
0
def add_or_update_admin(request):
    post_data = read_post_data(request)
    if "flytta" in post_data:
        for flytta_id in post_data["flytta"]:
            add_roller(post_data["kodstugor_id"][0], "volontär", flytta_id)
    elif "flera" in post_data:
        for i, namn in enumerate(post_data["namn"]):
            data = (
                post_data["namn"][i],
                post_data["epost"][i],
                phonenumber_to_format(post_data["telefon"][i]),
                arrow.get("2090-01-01").timestamp(),
            )
            try:
                db.cursor.execute("""
                    INSERT
                        INTO volontarer
                            (namn, epost, telefon, utdrag_datum)
                        VALUES
                            (?,?,?,?)
                    """, data)

                db.commit()
                add_roller(
                    post_data["kodstugor_id"][0],
                    "volontär",
                    get_id(post_data["epost"][i])
                )
                send_email(
                    post_data["epost"][i],
                    "BESK-konto aktiverat",
                    texter.get_one("BESK-konto aktiverat")["text"]
                )
            except db.sqlite3.IntegrityError:
                pass
    else:
        try:
            phone_number = phonenumbers.parse(post_data["telefon"][0], "SE")
            phone_number_str = phonenumbers.format_number(phone_number, phonenumbers.PhoneNumberFormat.E164)
        except Exception:
            raise Error400("Fyll i ett giltigt telefonummer.")
        if not phonenumbers.is_valid_number(phone_number):
            raise Error400("Fyll i ett giltigt telefonummer.")
        if "id" in post_data:
            data = (
                post_data["namn"][0],
                post_data["epost"][0],
                phone_number_str,
                arrow.get("2090-01-01").timestamp(),
                post_data["id"][0]
            )
            db.cursor.execute("""
                UPDATE volontarer
                    SET
                        namn = ?,
                        epost = ?,
                        telefon = ?,
                        utdrag_datum = ?
                    WHERE
                        id = ?
                """, data)
            db.commit()
            roll_list = []
            if "kodstugor_id" in post_data:
                for form_index, value in enumerate(post_data["kodstugor_id"]):
                    roll_list.append(
                        {
                            "kodstugor_id": value,
                            "roll": post_data["roller"][form_index]
                        }
                    )
                add_or_update_roller(roll_list, post_data["id"][0])
            else:
                add_or_update_roller([], post_data["id"][0])
        else:
            data = (
                post_data["namn"][0],
                post_data["epost"][0],
                phone_number_str,
                arrow.get("2090-01-01").timestamp(),
            )
            try:
                db.cursor.execute("""
                    INSERT
                        INTO volontarer
                            (namn, epost, telefon, utdrag_datum)
                        VALUES
                            (?,?,?,?)
                    """, data)
                db.commit()
                send_email(
                    post_data["epost"][0],
                    "BESK-konto aktiverat",
                    texter.get_one("BESK-konto aktiverat")["text"]
                )
                roll_list = []
                if "kodstugor_id" in post_data:
                    for form_index, value in enumerate(post_data["kodstugor_id"]):
                        roll_list.append(
                            {
                                "kodstugor_id": value,
                                "roll": post_data["roller"][form_index]
                            }
                        )
                    add_or_update_roller(roll_list, get_id(post_data["epost"][0]))
            except db.sqlite3.IntegrityError:
                raise Error400("E-Postadressen finns redan.")
Ejemplo n.º 39
0
def phonenumber_to_format(number):
    try:
        phone_number = phonenumbers.parse(number, "SE")
        return phonenumbers.format_number(phone_number, phonenumbers.PhoneNumberFormat.E164)
    except Exception:
        return "+46700000000"
Ejemplo n.º 40
0
    def _write_tweets(self, results):
        fieldnames_ = [
            'issue', 'action', 'id', 'es_score', 'tweet_timestamp',
            'query_timestamp', 'tweet_user', 'tweet_cities', 'tweet_states',
            'tweet_urls', 'tweet_phone_numbers', 'tweet_dates_ref',
            'tweet_legislator_names', 'tweet_legislator_handles', 'tweet'
        ]
        if self.tweets_firstline:
            self.tweets_firstline = False
            buffer = open("twitter_" + self.outfile, "w")
            # rzst_events table in Drupal MySQL backend.
            self.writer = csv.DictWriter(buffer, fieldnames=fieldnames_)
            self.writer.writeheader()
        # instantiate the row to be written as empty dict
        row = dict.fromkeys(fieldnames_, "")

        # iterate through each tweet
        n_results = len(results['hits']['hits'])
        if n_results > 0:
            print("Writing %s results.\n" % n_results)
            for result in tqdm(results['hits']['hits']):
                tweet = ""

                # potential for two KeyErrors, the second won't be caught
                # so use if statement instead.
                if 'message' in result['_source'].keys():
                    tweet = result['_source']['message']
                elif 'text' in result['_source'].keys():
                    tweet = result['_source']['text']
                else:
                    print("issue with document {id}".format(id=result['_id']))
                    print("From index {issue}-{date}".format(issue=self.issue,
                                                             date=self.date))
                    print(result['_source'])
                    # skip meetup for now
                    continue

                # EXTRACT PHONE NUMBER, URL, STATE, CITY, DATE, LEGISLATOR NAMES, AND LEGISLATOR TWITTER HANDLES #
                # -- Phone Numbers -- #
                phone_numbers = []
                phone_matches = phonenumbers.PhoneNumberMatcher(tweet, "US")
                while phone_matches.has_next():
                    number = phone_matches.next()
                    number = phonenumbers.format_number(
                        number.number, phonenumbers.PhoneNumberFormat.NATIONAL)
                    phone_numbers.append(number)
                phone_numbers = '; '.join(phone_numbers)

                # -- States -- #
                states = ''
                tweet_states = re.findall(state_regex, tweet)
                if tweet_states:
                    tweet_states = list(set(tweet_states))
                    states = '; '.join(tweet_states)

                # -- CITIES -- #
                cities = ''
                tweet_cities = re.findall(city_regex, tweet)
                if tweet_cities:
                    tweet_cities = list(
                        set([city.title() for city in tweet_cities]))
                    cities = '; '.join(tweet_cities)

                # -- URLS -- #
                urls = ''
                tweet_urls = re.findall(web_url_regex, tweet)
                if tweet_urls:
                    tweet_urls = list(set(tweet_urls))
                    # only select the first URL for inclusion on the homepage
                    urls = tweet_urls[0]

                # -- DATES -- #
                dates = ''
                doc = nlp(tweet)
                all_dates = [
                    doc.text for doc in doc.ents if doc.label_ == 'DATE'
                ]
                date_matches = re.findall(date_include_regex,
                                          ' '.join(all_dates))
                ### EXCLUDE SOME DIRTY DATES FROM TWITTER THAT SPACY MISTAKENLY INCLUDES
                if date_matches:
                    dates = all_dates[0]
                    #re.findall(date_exclude_regex,ent.text)

                # -- LEGISLATOR NAMES -- #
                leg_names = ''
                tweet_legislators = re.findall(leg_name_regex, tweet)
                tweet_legislators = list(set(tweet_legislators))
                leg_names = '; '.join(tweet_legislators)

                # -- LEGISLATOR TWITTER HANDLES -- #
                leg_twitter_handles = ''
                tweet_leg_handles = re.findall(leg_twitter_regex, tweet)
                tweet_leg_handles = list(set(tweet_leg_handles))
                if tweet_leg_handles:
                    leg_twitter_handles = '; '.join(tweet_leg_handles)

                # process if only first item is needed
                temp_row = {
                    'tweet_cities': cities,
                    'tweet_states': states,
                    'tweet_urls': urls,
                    'tweet_phone_numbers': phone_numbers,
                    'tweet_dates_ref': dates,
                    'tweet_legislator_names': leg_names,
                    'tweet_legislator_handles': leg_twitter_handles
                }

                if self.FIRST_MATCH:
                    temp_row = {key: value for key, value in temp_row.items()}

                # Replace commas in tweet to avoid confusing parser
                # when reading later.
                tweet = tweet.replace(",", "")

                # fill in the values to row
                row.update({
                    'issue': self.issue,
                    'action': self.action,
                    'id': result['_id'],
                    'es_score': result['_score'],
                    'tweet_timestamp': result['_source']['@timestamp'],
                    'query_timestamp': self.querytimestamp,
                    'tweet_user': result['_source']['user'],
                    # TODO: Ross to filter 'message' section of document for address
                    'tweet': tweet
                })
                row.update(temp_row)

                # skip retweets
                if row['tweet'][:2] == "RT":
                    continue
                self.writer.writerow(row)
                self.line_count['twitter'] += 1
        else:
            print("No results to save!")
            return None
Ejemplo n.º 41
0
 def to_string(self, obj):
     return phonenumbers.format_number(obj,
                                       phonenumbers.PhoneNumberFormat.E164)
Ejemplo n.º 42
0
def clean_phone(phone):
    # This could raise, but should have been checked with validate_phone first
    return phonenumbers.format_number(
        phonenumbers.parse(phone, DEFAULT_REGION),
        phonenumbers.PhoneNumberFormat.E164,
    )
Ejemplo n.º 43
0
 def international_phone_number(self):
     parsed_number = phonenumbers.parse(self.phone_number)
     return phonenumbers.format_number(parsed_number,
                                       PhoneNumberFormat.INTERNATIONAL)
Ejemplo n.º 44
0
 def get_InternationalFormat(self):
     return phonenumbers.format_number(
         self.phonenumber_object,
         phonenumbers.PhoneNumberFormat.INTERNATIONAL)
Ejemplo n.º 45
0
def normalize_phone(number):
    return phonenumbers.format_number(phonenumbers.parse(number, 'US'),
                                      phonenumbers.PhoneNumberFormat.E164)
Ejemplo n.º 46
0
 def get_RFC3966Format(self):
     return phonenumbers.format_number(
         self.phonenumber_object, phonenumbers.PhoneNumberFormat.RFC3966)
Ejemplo n.º 47
0
    def handleEvent(self, event):
        eventName = event.eventType
        srcModuleName = event.module
        eventData = event.data
        sourceData = self.sf.hashstring(eventData)

        if sourceData in self.results:
            return None
        else:
            self.results[sourceData] = True

        self.sf.debug("Received event, " + eventName + ", from " +
                      srcModuleName)

        if eventName in [
                'TARGET_WEB_CONTENT', 'DOMAIN_WHOIS', 'NETBLOCK_WHOIS'
        ]:
            # Make potential phone numbers more friendly to parse
            content = eventData.replace('.', '-')

            for match in phonenumbers.PhoneNumberMatcher(content, region=None):
                n = phonenumbers.format_number(
                    match.number, phonenumbers.PhoneNumberFormat.E164)
                evt = SpiderFootEvent("PHONE_NUMBER", n, self.__name__, event)
                if event.moduleDataSource:
                    evt.moduleDataSource = event.moduleDataSource
                else:
                    evt.moduleDataSource = "Unknown"
                self.notifyListeners(evt)

        if eventName == 'PHONE_NUMBER':
            try:
                number = phonenumbers.parse(eventData)
            except BaseException as e:
                self.sf.debug('Error parsing phone number: ' + str(e))
                return None

            try:
                number_carrier = carrier.name_for_number(number, 'en')
            except BaseException as e:
                self.sf.debug('Error retrieving phone number carrier: ' +
                              str(e))
                return None

            if number_carrier:
                evt = SpiderFootEvent("PROVIDER_TELCO", number_carrier,
                                      self.__name__, event)
                self.notifyListeners(evt)
            else:
                self.sf.debug("No carrier information found for " + eventData)

            #try:
            #    location = geocoder.description_for_number(number, 'en')
            #except BaseException as e:
            #    self.sf.debug('Error retrieving phone number location: ' + str(e))
            #    return None

            #if location:
            #    evt = SpiderFootEvent("GEOINFO", location, self.__name__, event)
            #    self.notifyListeners(evt)
            #else:
            #    self.sf.debug("No location information found for " + eventData)

        return None
Ejemplo n.º 48
0
 def get_standard_phone(self):
     n = self.get_phone()
     fmt = phonenumbers.PhoneNumberFormat.E164
     return phonenumbers.format_number(n, fmt)
Ejemplo n.º 49
0
 def format_phone_number(self, phone):
     try:
         return phonenumbers.format_number(phonenumbers.parse(phone, 'US'), phonenumbers.PhoneNumberFormat.NATIONAL)
     except Exception as e:
         print('Could not format phone number!')
         return None
Ejemplo n.º 50
0
 def format_as(self, format):
     if self.is_valid():
         return phonenumbers.format_number(self, format)
     else:
         return self.raw_input
Ejemplo n.º 51
0
 def get_national_phone(self):
     n = self.get_phone()
     fmt = phonenumbers.PhoneNumberFormat.NATIONAL
     return phonenumbers.format_number(n, fmt)
Ejemplo n.º 52
0
 def format_as(self, format):
     return phonenumbers.format_number(self, format)
def process_number(num):
    phone = phonenumbers.parse(num, "ZA")
    return phonenumbers.format_number(phone, phonenumbers.PhoneNumberFormat.E164)
Ejemplo n.º 54
0
 def __repr__(self):
     e164_number = phonenumbers.format_number(phonenumbers.parse(self.phone_number, 'US'),
                                              phonenumbers.PhoneNumberFormat.E164)
     return '<PhoneNumber {}>'.format(e164_number)
Ejemplo n.º 55
0
    def claim_number(self, user, phone_number, country, role):
        org = user.get_org()

        client = org.get_vonage_client()
        org_config = org.config

        matching_phones = client.get_numbers(phone_number)
        is_shortcode = False

        # try it with just the national code (for short codes)
        if not matching_phones:
            parsed = phonenumbers.parse(phone_number, None)
            shortcode = str(parsed.national_number)

            matching_phones = client.get_numbers(shortcode)

            if matching_phones:
                is_shortcode = True
                phone_number = shortcode

        # buy the number if we have to
        if not matching_phones:
            try:
                client.buy_number(country, phone_number)
                matching_phones = client.get_numbers(phone_number)
            except Exception as e:
                raise Exception(
                    _("There was a problem claiming that number, please check the balance on your account. "
                      "Note that you can only claim numbers after adding credit to your Vonage account."
                      ) + "\n" + str(e))

        # what does this number support?
        features = [elt.upper() for elt in matching_phones[0]["features"]]
        supports_msgs = "SMS" in features
        supports_voice = "VOICE" in features
        role = ""
        if supports_msgs:
            role += Channel.ROLE_SEND + Channel.ROLE_RECEIVE

        if supports_voice:
            role += Channel.ROLE_ANSWER + Channel.ROLE_CALL

        channel_uuid = generate_uuid()
        callback_domain = org.get_brand_domain()
        receive_url = "https://" + callback_domain + reverse(
            "courier.nx", args=[channel_uuid, "receive"])

        # if it supports voice, create new voice app for this number
        if supports_voice:
            app_id, app_private_key = client.create_application(
                org.get_brand_domain(), channel_uuid)
        else:
            app_id = None
            app_private_key = None

        # update the delivery URLs for it
        try:
            client.update_number(country, phone_number, receive_url, app_id)

        except Exception as e:  # pragma: no cover
            # shortcodes don't seem to claim correctly, move forward anyways
            if not is_shortcode:
                raise Exception(
                    _("There was a problem claiming that number, please check the balance on your account."
                      ) + "\n" + str(e))

        if is_shortcode:
            phone = phone_number
            vonage_phone_number = phone_number
        else:
            parsed = phonenumbers.parse(phone_number, None)
            phone = phonenumbers.format_number(
                parsed, phonenumbers.PhoneNumberFormat.INTERNATIONAL)

            # vonage ships numbers around as E164 without the leading +
            vonage_phone_number = phonenumbers.format_number(
                parsed, phonenumbers.PhoneNumberFormat.E164).strip("+")

        config = {
            Channel.CONFIG_VONAGE_APP_ID: app_id,
            Channel.CONFIG_VONAGE_APP_PRIVATE_KEY: app_private_key,
            Channel.CONFIG_VONAGE_API_KEY: org_config[Org.CONFIG_VONAGE_KEY],
            Channel.CONFIG_VONAGE_API_SECRET:
            org_config[Org.CONFIG_VONAGE_SECRET],
            Channel.CONFIG_CALLBACK_DOMAIN: callback_domain,
        }

        channel = Channel.create(
            org,
            user,
            country,
            self.channel_type,
            name=phone,
            address=phone_number,
            role=role,
            config=config,
            bod=vonage_phone_number,
            uuid=channel_uuid,
            tps=1,
        )

        return channel
Ejemplo n.º 56
0
 def number_exists(phone_number):
     phone_number = phonenumbers.format_number(phonenumbers.parse(phone_number, 'US'), phonenumbers.PhoneNumberFormat.E164)
     return PhoneNumber.query.filter_by(phone_number=phone_number).count()
Ejemplo n.º 57
0
def signup():
    error = None
    if request.method == 'POST':
        addresslist = []
        try:
            _username = str(request.form['username'])
            _password = str(request.form['password'])
        except:
            error = 'There is an error with your username/password.'
            return render_template('signup.html', error=error)
        try:
            phonenumber = str(request.form['phonenumber'])
            print phonenumber
            phonenumObject = ph.parse(phonenumber, None)
            if not ph.is_valid_number(phonenumObject):
                raise Exception
        except:
            error = 'Invalid Phone Number.'
            return render_template('signup.html', error=error)
        _phonenumber = str(ph.format_number(phonenumObject, ph.PhoneNumberFormat.E164))
        try:
            _address1 = str(request.form['address1'])
            _starttime1 = int(request.form['starttime1'])
            _endtime1 = int(request.form['endtime1'])
            # parse address into lat lng
            try:
                geocode_result = gmaps.geocode(_address1)
                if len(geocode_result) == 0:
                    raise Exception
                #get the lat,long of the address
                _addresspoint1 = geocode_result[0]['geometry']['location'].values()[0], geocode_result[0]['geometry']['location'].values()[1]
                #the _addresspoint1 tuple is flipped around because PostGIS uses long,lat instead of lat,long
                cur.execute("SELECT ST_SetSRID(ST_MakePoint('{}', '{}'), 4326)".format(_addresspoint1[1],_addresspoint1[0]))
                _geog1 = cur.fetchall()[0][0]
            except:
                error = "First address is invalid.{}".format(_addresspoint1)
                return render_template('signup.html', error=error)
            if _starttime1 >= _endtime1:
                raise Exception
            addresslist.append([_address1, _addresspoint1, _starttime1, _endtime1, _geog1])
        except:
            error = "There is an issue with your first address/timings."
            return render_template('signup.html', error=error)
        if request.form['address2']:
            try:
                _address2 = str(request.form['address2'])
                _starttime2 = int(request.form['starttime2'])
                _endtime2 = int(request.form['endtime2'])
                #parse address into lat long here
                try:
                    geocode_result = gmaps.geocode(_address2)
                    if len(geocode_result) == 0:
                        raise Exception
                    _addresspoint2 = geocode_result[0]['geometry']['location'].values()[0], geocode_result[0]['geometry']['location'].values()[1] 
                    cur.execute("SELECT ST_SetSRID(ST_MakePoint('{}', '{}'), 4326)".format(_addresspoint2[1],_addresspoint2[0]))
                    _geog2 = cur.fetchall()[0][0]
                except:
                    error = "Second address is invalid."
                    return render_template('signup.html', error=error)
                            
                if _starttime2 >= _endtime2:
                    raise Exception
                addresslist.append([_address2, _addresspoint2, _starttime2, _endtime2, _geog2])
            except:
                error = "There is an issue with your second address/timings."
                return render_template('signup.html', error=error)               
        if request.form['address3']:
            try:
                _address3 = str(request.form['address3'])
                _starttime3 = int(request.form['starttime3'])
                _endtime3 = int(request.form['endtime3'])
                #parse address into lat long here
                try:
                    geocode_result = gmaps.geocode(_address3)
                    if len(geocode_result) == 0:
                        raise Exception
                    _addresspoint3 = geocode_result[0]['geometry']['location'].values()[0], geocode_result[0]['geometry']['location'].values()[1]
                    cur.execute("SELECT ST_SetSRID(ST_MakePoint('{}', '{}'), 4326)".format(_addresspoint3[1],_addresspoint3[0]))
                    _geog3 = cur.fetchall()[0][0]
                except:
                    error = "Third address is invalid."
                    return render_template('signup.html', error=error)
                   
                if _starttime3 >= _endtime3:
                    raise Exception
                addresslist.append([_address3, _addresspoint3, _starttime3, _endtime3, _geog3])
            except:
                error = "There is an issue with your third address/timings."
                return render_template('signup.html', error=error)
        try:
            file = request.files['file']
            _filename = file.filename
            print _filename
            _filedata = db.Binary(file.read())
        except:
            error = "There is an issue with your uploaded file.{}".format(request.form)
            return render_template('signup.html', error=error)
        try:
            cur.execute("INSERT INTO medics (username, password, phonenumber, active, filename, filedata, validated, pending)\
        VALUES ('{}', '{}', '{}', True, '{}', {}, False, True)".format(_username, _password, _phonenumber, _filename, _filedata))
            for infolist in addresslist:
                cur.execute("INSERT INTO addresses (username, address, addresspoint, starttime, endtime, geog)\
                VALUES('{}', '{}', '{}', '{}', '{}', '{}')".format(_username, infolist[0], infolist[1], infolist[2], infolist[3], infolist[4]))
        except:
            error = 'Unable to insert into database.'
            return render_template('signup.html', error=error)
        session['username'] = _username
        con.commit()
        if session['username'] == 'admin':
            return redirect('/admin')
        return redirect('user/'+session['username'])
    return render_template('signup.html')
Ejemplo n.º 58
0
 def clean_phone_number(self):
     phone = self.cleaned_data["phone_number"]
     phone = phonenumbers.parse(phone, self.cleaned_data["country"])
     return phonenumbers.format_number(phone, phonenumbers.PhoneNumberFormat.E164)
Ejemplo n.º 59
0
def normalize_phone(number):
    number = number[1:] if number[:1] == '0' else number
    parse_phone_number = phonenumbers.parse(number, 'ID')
    phone_number = phonenumbers.format_number(
        parse_phone_number, phonenumbers.PhoneNumberFormat.E164)
    return phone_number
Ejemplo n.º 60
0
def normalize_phone(phone):
    phone_parsed = phonenumbers.parse(phone, region="DE")
    return phonenumbers.format_number(phone_parsed, phonenumbers.PhoneNumberFormat.E164)