Commits

Mikhail Korobov committed 8956b78

more methods are implemented; Imobis class. Bump version.

  • Participants
  • Parent commits 13924a3
  • Tags 0.2

Comments (0)

Files changed (5)

 Usage
 =====
 
-Only sms sending is implemented in imobis 0.1.
-
 ::
 
-    >>> from imobis.api import sms_send
-    >>> res = api.sms_send('login', 'password', 'Sender', '79991234567', u'привет', message_id=5234)
+    >>> from imobis.api import Imobis
+    >>> im = Imobis('login', 'password')
+
+Send sms::
+
+    >>> im.send_sms('Sender', '79991234567', u'привет', message_id=5234)
     12836
 
+Get balance::
+
+    >>> im.get_balance()
+    100
+
+Check if phone number is valid::
+
+    >>> im.is_valid_phone('234234')
+    False
+
+
 Development
 -----------
 

File imobis/api.py

 from __future__ import absolute_import, unicode_literals
 import re
 import binascii
+from xml.etree import ElementTree
 from .compat import urlopen, urlencode
 
-GATE_URL = 'http://gate.sms-manager.ru/_getsmsd.php'
 REMOVE_RE = re.compile(r'[\s\(\)\-]', re.U)
 
 class ImobisError(Exception):
     return phone
 
 
-def sms_send(user, password, sender, phone, message, message_id=None, timeout=10, gate_url=GATE_URL):
-    """
-    Sends SMS. Returns internal_id.
-    """
-    data = {
-        'user': user,
-        'password': password,
-        'sender': sender,
-        'GSM': normalize_phone(phone),
-        'binary': encode_to_binary(message)
-    }
-    if message_id:
-        data['messageId'] = message_id
+class Imobis(object):
+    GATE_URL = 'http://gate.sms-manager.ru/_getsmsd.php'
+    BALANCE_URL = 'http://gate.sms-manager.ru/_balance.php'
+    CHECK_URL = 'http://gate.sms-manager.ru/_checkgsm.php'
 
-    query = urlencode(data)
-    url = gate_url+'?'+query
-    result = int(urlopen(url.encode('utf8'), timeout=timeout).read())
+    def __init__(self, user, password, timeout=10):
+        self.user = user
+        self.password = password
+        self.timeout = timeout
 
-    if result < 0:
-        raise ImobisError(result)
+    def send_sms(self, sender, phone, message, message_id=None):
+        """
+        Sends SMS. Returns internal_id.
+        """
+        data = {
+            'sender': sender,
+            'GSM': normalize_phone(phone),
+            'binary': encode_to_binary(message)
+        }
+        if message_id is not None:
+            data['messageId'] = message_id
 
-    return int(result)
+        result = int(self._http_get(self.GATE_URL, data))
 
+        if result < 0:
+            raise ImobisError(result)
 
+        return result
+
+    def get_balance(self):
+        """
+        Returns current balance.
+        """
+        return self._http_get(self.BALANCE_URL, {}).decode('utf8')
+
+    def is_valid_phone(self, phone):
+        """
+        Checks if phone is valid and returns True or False.
+        """
+        res = self._http_get(self.CHECK_URL, {
+            'GSM': normalize_phone(phone),
+            'mode': 'brief',
+        }).decode('utf8')
+
+        if res == 'OK':
+            return True
+        if res == 'noBindingDetected':
+            return False
+
+        try:
+            code = int(res)
+            raise ImobisError(code)
+        except ValueError:
+            raise ImobisError(res)
+
+# TODO:
+#    def get_phone_info(self, phone):
+#        """
+#        Returns phone info: dict(
+#            region='Санкт-Петербург',
+#            operator='ОАО "Мобильные Телесистемы"',
+#            issuedate='2001-10-18'
+#        )
+#
+#        or None if phone is invalid.
+#        """
+#
+#        res = self._http_get(self.CHECK_URL, {
+#            'GSM': normalize_phone(phone),
+#            'mode': 'full',
+#        }).decode('utf8')
+#
+#        xml = ElementTree.fromstring(res)
+#        return xml
+
+
+    def _http_get(self, url, data):
+        _data = {'user': self.user, 'password': self.password}
+        _data.update(data)
+        url = url + '?' + urlencode(_data)
+        return urlopen(url.encode('utf8'), timeout=self.timeout).read()

File imobis/tests.py

 from . import api
 from .compat import urlparse
 
-class ApiTest(unittest.TestCase):
-    def assertUrlQueryEqual(self, url1, url2):
-        data1 = urlparse.urlsplit(url1)
-        data2 = urlparse.urlsplit(url2)
-        q1 = urlparse.parse_qs(data1.query)
-        q2 = urlparse.parse_qs(data2.query)
-        self.assertEqual(q1, q2)
-
+class UtilsTest(unittest.TestCase):
     def test_binary_encode(self):
         self.assertEqual(api.encode_to_binary('привет'), b'043f04400438043204350442')
 
         self.assertEqual(api.normalize_phone('8(999)1234-567'), '79991234567')
         self.assertEqual(api.normalize_phone('89991234567'), '79991234567')
 
-    @mock.patch('imobis.api.urlopen')
+
+@mock.patch('imobis.api.urlopen')
+class ApiTest(unittest.TestCase):
+
+    def setUp(self):
+        self.im = api.Imobis('login', 'password')
+
+    def assertUrlQueryEqual(self, url1, url2):
+        data1 = urlparse.urlsplit(url1)
+        data2 = urlparse.urlsplit(url2)
+        q1 = urlparse.parse_qs(data1.query)
+        q2 = urlparse.parse_qs(data2.query)
+        self.assertEqual(q1, q2)
+
+
     def test_send_sms(self, urlopen):
         urlopen.return_value.read.return_value = b'124'
+        url = b'http://gate.sms-manager.ru/_getsmsd.php?user=login&password=password&sender=Pan%20Gurman&binary=043f04400438043204350442&GSM=79991234567&messageId=5'
 
-        url = b'http://gate.sms-manager.ru/_getsmsd.php?user=login&password=password&sender=Pan%20Gurman&binary=043f04400438043204350442&GSM=79991234567&messageId=5'
-        res = api.sms_send('login', 'password', 'Pan Gurman', '8 (999) 1234-567', 'привет', 5)
+        res = self.im.send_sms('Pan Gurman', '8 (999) 1234-567', 'привет', 5)
 
         request_url = urlopen.call_args[0][0]
         self.assertUrlQueryEqual(request_url, url)
 
         self.assertEqual(res, 124)
 
-    @mock.patch('imobis.api.urlopen')
     def test_sms_send_str(self, urlopen):
         urlopen.return_value.read.return_value = b'124'
         url = b'http://gate.sms-manager.ru/_getsmsd.php?user=login&password=password&sender=Pan%20Gurman&binary=043f04400438043204350442&GSM=79991234567'
-        res = api.sms_send(b'login', b'password', b'Pan Gurman', '8 (999) 1234-567', 'привет')
+
+        im = api.Imobis(b'login', b'password')
+        res = im.send_sms(b'Pan Gurman', '8 (999) 1234-567', 'привет')
 
         request_url = urlopen.call_args[0][0]
         self.assertUrlQueryEqual(request_url, url)
 
         self.assertEqual(res, 124)
 
-    @mock.patch('imobis.api.urlopen')
     def test_errors(self, urlopen):
         urlopen.return_value.read.return_value = b'-1'
 
         raised = False
         try:
-            api.sms_send('login', 'password', 'Pan Gurman', '8 (999) 1234-567', 'привет', 5)
+            self.im.send_sms('Pan Gurman', '8 (999) 1234-567', 'привет')
         except api.ImobisError as e:
             self.assertEqual(e._code, -1)
             self.assertEqual(e.message(), 'Ошибка отправки')
             raised = True
         self.assertTrue(raised)
 
+    def test_balance(self, urlopen):
+        urlopen.return_value.read.return_value = b'100'
+        self.assertEqual(self.im.get_balance(), '100')
+
+    def test_is_valid_phone(self, urlopen):
+        urlopen.return_value.read.return_value = b'OK'
+        self.assertTrue(self.im.is_valid_phone('1234234234'))
+
+    def test_is_valid_phone_error(self, urlopen):
+        urlopen.return_value.read.return_value = b'-10'
+
+        def fetch():
+            return self.im.is_valid_phone('123423412')
+
+        self.assertRaises(api.ImobisError, fetch)
+
     # python3 doesn't need this
     pass
 
-version='0.1'
+version='0.2'
 
 setup(
     name='imobis',
 
 [testenv]
 deps=
-    django
     mock==0.8
     nose
     coverage
 
 [testenv:py32]
 deps=
-    https://bitbucket.org/vinay.sajip/django/get/tip.zip#egg=django
     mock==0.8
     nose
     coverage