Exemplo n.º 1
0
    def test_1(self):
        ph = PhoneNumber("+1(858)775-2868")

        self.assertEqual("+1(858)775-2868", ph.original_value)
        self.assertEqual("+18587752868", ph.stripped_value)
        self.assertEqual("(858)775-2868", ph.get_value_as_north_america())
        self.assertEqual("+1.858.775.2868", ph.get_value_as_international())
Exemplo n.º 2
0
    def test_3(self):
        ph = PhoneNumber("+598.123.4567x858")

        self.assertEqual("+598.123.4567x858", ph.original_value)
        self.assertEqual("+5981234567x858", ph.stripped_value)
        self.assertEqual("", ph.get_value_as_north_america())
        self.assertEqual("+598.123.456.7x858", ph.get_value_as_international())
Exemplo n.º 3
0
    def get_prep_value(self, value):
        """
        Generate field's value prepared for saving into a database.
        
        Since using a database requires conversion in both ways, if you override
        `to_python()` you also have to override `get_prep_value()` to convert
        python objects back to query values.
        
        Args:
            value: an instance of PhoneNumber
    
        Returns:
            A string type since this field uses CharField as its internal type.
        """
        if value is None or value == '':
            phone_number_obj = PhoneNumber.to_python(self.default)
            if phone_number_obj:
                return phone_number_object.as_e164
            else:
                return ''

        value = PhoneNumber.to_python(value)
        if isinstance(value, six.string_types):
            # it is an invalid phone number
            return value
        return value.as_e164
Exemplo n.º 4
0
def auth(number, get_pin_callback=raw_input):
    """
    Return an authorization key for a phone number.
    The get_pin_callback should return the access code sent by SMS.
    """
    number = PhoneNumber(number)
    assert number.is_belgian_gsm()

    # 1. Register
    query = '<register appId="%s" phoneNumber="%s"/>' % (APP_ID, str(number))
    response = _request(query)
    assert '<result code="100">' in response.content

    # 2. Confirmation code
    pin_code = get_pin_callback("Confirmation code (SMS sent to %s) ? " % (
        repr(number)
    ))
    query = ''.join((
        '<sendRegistrationCode ',
        'appId="%s" ' % (APP_ID),
        'phoneNumber="%s" ' % (number),
        'code="%s"/>' % (pin_code)
    ))
    response = _request(query)
    assert '<result code="100">' in response.content
    return _extract_message(response.content)
Exemplo n.º 5
0
    def test_4(self):
        ph = PhoneNumber("+27 1234 5678 ext 4")

        self.assertEqual("+27 1234 5678 ext 4", ph.original_value)
        self.assertEqual("+2712345678x4", ph.stripped_value)
        self.assertEqual("", ph.get_value_as_north_america())
        self.assertEqual("+27 1234 5678 ext 4",
                         ph.get_value_as_international())
Exemplo n.º 6
0
def send_sms(token, message, recipient):
    number = PhoneNumber(recipient)
    assert number.is_belgian_gsm()

    query = ''.join((
        '<sendSMS appId="%s">' % (APP_ID),
        '<key>%s</key>' % (token),
        '<text><![CDATA[%s]]></text>' % (message),
        '<phoneNumber>%s</phoneNumber>' % (str(number)),
        '</sendSMS>'
    ))
    response = _request(query)
    assert '<result code="100">' in response.content
    return _extract_message(response.content)
Exemplo n.º 7
0
def send_message(phone, message):
	phn = PhoneNumber(phone)
	phone = phn.valid_numbers()
	if phone:
		today = datetime.datetime.now()
		messages = mongo.db['outbox']
		messages.insert({'sender': 'Identity', 'message':message, 'recipient': phone, 'date': today})
		protocol = Messenger(phone, message)
		sent, failed, amount = protocol.send_message()
		if sent:
			messages.update_one({'recipient': phone, 'message': message}, {'$set': {'status': True, 'amount': amount}})
		elif failed:
			messages.update_one({'recipient': phone, 'message': message}, {'$set': {'status': False, 'amount': 0}})
	else:
		print "Invalid phone number"
Exemplo n.º 8
0
 def update_phone(self, typ, value):
     if (typ == WORK_TYPE and not self.work_phone) or (typ == CELL_TYPE and not self.cell_phone):
         self.phonenumbers.append(PhoneNumber(value, typ))
         return True
     else:
         for ph in self.phonenumbers:
             if ph.type == typ:
                 ph.full_phonenumber = value
                 return True
     return False
Exemplo n.º 9
0
    def to_representation(self, obj):
        """
        Convert a PhoneNumber instance into a primitive, serializable datatype.
        
        Args:
            obj: an instance of PhoneNumber
    
        Returns:
            A string type
        """
        if obj is None:
            return obj

        obj = PhoneNumber.to_python(obj)
        if isinstance(obj, six.string_types):
            # it is an invalid phone number
            return obj
        return obj.as_e164
Exemplo n.º 10
0
    def to_internal_value(self, value):
        """
        Restore a primitive datatype into its PhoneNumber representation.
        
        Args:
            value: The number that we are attempting to parse. This can be:
                * an instance of PhoneNumber
                * a string representing phone number
                * invalid data
    
        Returns:
            A PhoneNumber class instance
        """
        phone_number = PhoneNumber.to_python(value)

        if phone_number and not phone_number.is_valid():
            raise serializers.ValidationError(self.error_messages['invalid'])

        return phone_number
Exemplo n.º 11
0
    def to_python(self, value):
        """
        Parse a phone number and return a corresponding PhoneNumber object.
        This method is more robust than from_string as it has more checks
        and handles the exceptions.
        
        Args:
            value: The number that we are attempting to parse. This can be:
                * an instance of PhoneNumber
                * a string representing phone number
                * None (if the field allows null=True)
                * invalid data
    
        Returns:
            A PhoneNumber class instance
        """
        phone_number = PhoneNumber.to_python(value)

        if phone_number and not phone_number.is_valid():
            raise ValidationError("Invalid input for a PhoneNumber instance")
        return phone_number
Exemplo n.º 12
0
 def to_python(self, value):
     phone_number = PhoneNumber.to_python(value)
     if phone_number and not phone_number.is_valid():
         raise ValidationError(self.error_messages['invalid'])
     return phone_number