diff options
| author | Devendra | 2014-04-23 14:03:13 +0530 | 
|---|---|---|
| committer | Devendra | 2014-04-23 14:03:13 +0530 | 
| commit | 09cd0c015ae276aa849297a6a976065b2b3f247b (patch) | |
| tree | f1b253aa856e3a16e36eea9213857a33f6c35df4 /common | |
| parent | fdb46e56fa6794940f9fbe51a2863d58e927e655 (diff) | |
| download | pubnub-python-09cd0c015ae276aa849297a6a976065b2b3f247b.tar.bz2 | |
modifying code for pep 8 compliance
Diffstat (limited to 'common')
| -rw-r--r-- | common/PubnubBase.py | 226 | ||||
| -rw-r--r-- | common/PubnubCore.py | 53 | ||||
| -rw-r--r-- | common/PubnubCoreAsync.py | 146 | ||||
| -rw-r--r-- | common/PubnubCrypto.py | 63 | ||||
| -rw-r--r-- | common/PubnubUnitTest.py | 59 | ||||
| -rw-r--r-- | common/unit-test-async.py | 94 | 
6 files changed, 337 insertions, 304 deletions
| diff --git a/common/PubnubBase.py b/common/PubnubBase.py index 14ae6c4..5863da9 100644 --- a/common/PubnubBase.py +++ b/common/PubnubBase.py @@ -1,32 +1,37 @@ -try: import json -except ImportError: import simplejson as json +try: +    import json +except ImportError: +    import simplejson as json  import time  import hashlib  import uuid  import sys -try: from urllib.parse  import quote -except: from urllib2 import quote +try: +    from urllib.parse import quote +except: +    from urllib2 import quote -from base64  import urlsafe_b64encode +from base64 import urlsafe_b64encode  from hashlib import sha256  import hmac +  class PubnubBase(object):      def __init__(          self,          publish_key,          subscribe_key, -        secret_key = False, -        cipher_key = False, -        auth_key = None, -        ssl_on = False, -        origin = 'pubsub.pubnub.com', -        UUID = None -    ) : +        secret_key=False, +        cipher_key=False, +        auth_key=None, +        ssl_on=False, +        origin='pubsub.pubnub.com', +        UUID=None +    ):          """          #**          #* Pubnub @@ -38,41 +43,41 @@ class PubnubBase(object):          #* @param string secret_key optional key to sign messages.          #* @param boolean ssl required for 2048 bit encrypted messages.          #* @param string origin PUBNUB Server Origin. -        #* @param string pres_uuid optional identifier for presence (auto-generated if not supplied) +        #* @param string pres_uuid optional identifier +        #*    for presence (auto-generated if not supplied)          #**          ## Initiat Class          pubnub = Pubnub( 'PUBLISH-KEY', 'SUBSCRIBE-KEY', 'SECRET-KEY', False )          """ -        self.origin        = origin -        self.limit         = 1800 -        self.publish_key   = publish_key +        self.origin = origin +        self.limit = 1800 +        self.publish_key = publish_key          self.subscribe_key = subscribe_key -        self.secret_key    = secret_key -        self.cipher_key    = cipher_key -        self.ssl           = ssl_on -        self.auth_key      = auth_key - +        self.secret_key = secret_key +        self.cipher_key = cipher_key +        self.ssl = ssl_on +        self.auth_key = auth_key -        if self.ssl : +        if self.ssl:              self.origin = 'https://' + self.origin -        else : -            self.origin = 'http://'  + self.origin -         +        else: +            self.origin = 'http://' + self.origin +          self.uuid = UUID or str(uuid.uuid4())          if type(sys.version_info) is tuple: -            self.python_version  = 2 -            self.pc              = PubnubCrypto2() +            self.python_version = 2 +            self.pc = PubnubCrypto2()          else:              if sys.version_info.major == 2: -                self.python_version  = 2 -                self.pc              = PubnubCrypto2() +                self.python_version = 2 +                self.pc = PubnubCrypto2()              else:                  self.python_version = 3 -                self.pc             = PubnubCrypto3() -         +                self.pc = PubnubCrypto3() +          if not isinstance(self.uuid, str):              raise AttributeError("pres_uuid must be a string") @@ -93,7 +98,7 @@ class PubnubBase(object):          return signature      ''' -    def _pam_sign( self, msg ): +    def _pam_sign(self, msg):          """Calculate a signature by secret key and message."""          return urlsafe_b64encode(hmac.new( @@ -102,7 +107,7 @@ class PubnubBase(object):              sha256          ).digest()) -    def _pam_auth( self, query , apicode=0, callback=None): +    def _pam_auth(self, query, apicode=0, callback=None):          """Issue an authenticated request."""          if 'timestamp' not in query: @@ -129,57 +134,50 @@ class PubnubBase(object):          query['signature'] = self._pam_sign(sign_input) -        ''' -        url = ("https://pubsub.pubnub.com/v1/auth/{apitype}/sub-key/".format(apitype="audit" if (apicode) else "grant") + -            self.subscribe_key + "?" + -            params + "&signature=" + -            quote(signature, safe="")) -        ''' -          return self._request({"urlcomponents": [ -            'v1', 'auth', "audit" if (apicode) else "grant" ,  +            'v1', 'auth', "audit" if (apicode) else "grant",              'sub-key',              self.subscribe_key -        ], 'urlparams' : query},  -        self._return_wrapped_callback(callback)) +        ], 'urlparams': query}, +            self._return_wrapped_callback(callback)) -    def grant( self, channel, authkey=False, read=True, write=True, ttl=5, callback=None): +    def grant(self, channel, authkey=False, read=True, +              write=True, ttl=5, callback=None):          """Grant Access on a Channel."""          return self._pam_auth({ -            "channel" : channel, -            "auth"    : authkey, -            "r"       : read  and 1 or 0, -            "w"       : write and 1 or 0, -            "ttl"     : ttl +            "channel": channel, +            "auth": authkey, +            "r": read and 1 or 0, +            "w": write and 1 or 0, +            "ttl": ttl          }, callback=callback) -    def revoke( self, channel, authkey=False, ttl=1, callback=None): +    def revoke(self, channel, authkey=False, ttl=1, callback=None):          """Revoke Access on a Channel."""          return self._pam_auth({ -            "channel" : channel, -            "auth"    : authkey, -            "r"       : 0, -            "w"       : 0, -            "ttl"     : ttl +            "channel": channel, +            "auth": authkey, +            "r": 0, +            "w": 0, +            "ttl": ttl          }, callback=callback)      def audit(self, channel=False, authkey=False, callback=None):          return self._pam_auth({ -            "channel" : channel, -            "auth"    : authkey -        },1, callback=callback) -             - +            "channel": channel, +            "auth": authkey +        }, 1, callback=callback)      def encrypt(self, message):          if self.cipher_key: -            message = json.dumps(self.pc.encrypt(self.cipher_key, json.dumps(message)).replace('\n','')) -        else : +            message = json.dumps(self.pc.encrypt( +                self.cipher_key, json.dumps(message)).replace('\n', '')) +        else:              message = json.dumps(message) -        return message; +        return message      def decrypt(self, message):          if self.cipher_key: @@ -190,15 +188,17 @@ class PubnubBase(object):      def _return_wrapped_callback(self, callback=None):          def _new_format_callback(response):              if 'payload' in response: -                if (callback != None): callback({'message' : response['message'], 'payload' : response['payload']}) +                if (callback is not None): +                    callback({'message': response['message'], +                              'payload': response['payload']})              else: -                if (callback != None):callback(response) -        if (callback != None): +                if (callback is not None): +                    callback(response) +        if (callback is not None):              return _new_format_callback          else:              return None -      def publish(channel, message, callback=None, error=None):          """          #** @@ -232,10 +232,11 @@ class PubnubBase(object):              channel,              '0',              message -        ], 'urlparams' : {'auth' : self.auth_key}}, callback=self._return_wrapped_callback(callback),  -        error=self._return_wrapped_callback(error)) -     -    def presence( self, channel, callback, error=None) : +        ], 'urlparams': {'auth': self.auth_key}}, +            callback=self._return_wrapped_callback(callback), +            error=self._return_wrapped_callback(error)) + +    def presence(self, channel, callback, error=None):          """          #**          #* presence @@ -254,13 +255,15 @@ class PubnubBase(object):          pubnub.presence({              'channel'  : 'hello_world', -            'callback' : receive  +            'callback' : receive          })          """ -        return self.subscribe({'channel': channel+'-pnpres', 'subscribe_key':self.subscribe_key, 'callback': self._return_wrapped_callback(callback)}) -     -     -    def here_now( self, channel, callback, error=None) : +        return self.subscribe({ +            'channel': channel + '-pnpres', +            'subscribe_key': self.subscribe_key, +            'callback': self._return_wrapped_callback(callback)}) + +    def here_now(self, channel, callback, error=None):          """          #**          #* Here Now @@ -281,33 +284,31 @@ class PubnubBase(object):          """          channel = str(args['channel']) - -        callback    = args['callback']  if 'callback'  in args else None -        error       = args['error']     if 'error'     in args else None +        callback = args['callback'] if 'callback' in args else None +        error = args['error'] if 'error' in args else None          ## Fail if bad input. -        if not channel : +        if not channel:              raise Exception('Missing Channel')              return False -         +          ## Get Presence Here Now          return self._request({"urlcomponents": [ -            'v2','presence', +            'v2', 'presence',              'sub_key', self.subscribe_key,              'channel', channel -        ], 'urlparams' : {'auth' : self.auth_key}}, callback=self._return_wrapped_callback(callback),  -        error=self._return_wrapped_callback(error)) +        ], 'urlparams': {'auth': self.auth_key}}, +            callback=self._return_wrapped_callback(callback), +            error=self._return_wrapped_callback(error)) -    def history(self, channel, count=100, reverse=False, start=None, end=None, callback=None, error=None) : +    def history(self, channel, count=100, reverse=False, +                start=None, end=None, callback=None, error=None):          """          #**          #* History          #*          #* Load history from a channel.          #* -        #* @param array args with 'channel', optional: 'start', 'end', 'reverse', 'count' -        #* @return mixed false on fail, array on success. -        #*          ## History Example          history = pubnub.detailedHistory({ @@ -318,25 +319,26 @@ class PubnubBase(object):          """ -        params = dict()  +        params = dict() -        params['count']     = count -        params['reverse']   = reverse -        params['start']     = start -        params['end']       = end +        params['count'] = count +        params['reverse'] = reverse +        params['start'] = start +        params['end'] = end          ## Get History -        return self._request({ 'urlcomponents' : [ +        return self._request({'urlcomponents': [              'v2',              'history',              'sub-key',              self.subscribe_key,              'channel',              channel, -        ], 'urlparams' : {'auth' : self.auth_key}}, callback=self._return_wrapped_callback(callback),  -        error=self._return_wrapped_callback(error)) +        ], 'urlparams': {'auth': self.auth_key}}, +            callback=self._return_wrapped_callback(callback), +            error=self._return_wrapped_callback(error)) -    def time(self,callback=None) : +    def time(self, callback=None):          """          #**          #* Time @@ -352,28 +354,28 @@ class PubnubBase(object):          """ -        time = self._request({'urlcomponents' : [ +        time = self._request({'urlcomponents': [              'time',              '0'          ]}, callback) -        if time != None: +        if time is not None:              return time[0] - -    def _encode( self, request ) : +    def _encode(self, request):          return [ -            "".join([ ' ~`!@#$%^&*()+=[]\\{}|;\':",./<>?'.find(ch) > -1 and -                hex(ord(ch)).replace( '0x', '%' ).upper() or -                ch for ch in list(bit) -            ]) for bit in request] -     -    def getUrl(self,request): +            "".join([' ~`!@#$%^&*()+=[]\\{}|;\':",./<>?'.find(ch) > -1 and +                     hex(ord(ch)).replace('0x', '%').upper() or +                     ch for ch in list(bit) +                     ]) for bit in request] + +    def getUrl(self, request):          ## Build URL          url = self.origin + '/' + "/".join([ -            "".join([ ' ~`!@#$%^&*()+=[]\\{}|;\':",./<>?'.find(ch) > -1 and -                hex(ord(ch)).replace( '0x', '%' ).upper() or -                ch for ch in list(bit) -            ]) for bit in request["urlcomponents"]]) +            "".join([' ~`!@#$%^&*()+=[]\\{}|;\':",./<>?'.find(ch) > -1 and +                     hex(ord(ch)).replace('0x', '%').upper() or +                     ch for ch in list(bit) +                     ]) for bit in request["urlcomponents"]])          if ("urlparams" in request): -            url = url + '?' + "&".join([ x + "=" + str(y)  for x,y in request["urlparams"].items() if y is not None]) +            url = url + '?' + "&".join([x + "=" + str(y) for x, y in request[ +                "urlparams"].items() if y is not None])          return url diff --git a/common/PubnubCore.py b/common/PubnubCore.py index 7fb67d6..1c00215 100644 --- a/common/PubnubCore.py +++ b/common/PubnubCore.py @@ -3,13 +3,13 @@ class PubnubCore(PubnubCoreAsync):          self,          publish_key,          subscribe_key, -        secret_key = False, -        cipher_key = False, -        auth_key = None, -        ssl_on = False, -        origin = 'pubsub.pubnub.com', -        uuid = None -    ) : +        secret_key=False, +        cipher_key=False, +        auth_key=None, +        ssl_on=False, +        origin='pubsub.pubnub.com', +        uuid=None +    ):          """          #**          #* Pubnub @@ -21,7 +21,8 @@ class PubnubCore(PubnubCoreAsync):          #* @param string secret_key optional key to sign messages.          #* @param boolean ssl required for 2048 bit encrypted messages.          #* @param string origin PUBNUB Server Origin. -        #* @param string pres_uuid optional identifier for presence (auto-generated if not supplied) +        #* @param string pres_uuid optional +        #*  identifier for presence (auto-generated if not supplied)          #**          ## Initiat Class @@ -37,16 +38,14 @@ class PubnubCore(PubnubCoreAsync):              ssl_on=ssl_on,              origin=origin,              UUID=uuid -        )         +        )          self.subscriptions = {} -        self.timetoken     = 0 -        self.version       = '3.4' +        self.timetoken = 0 +        self.version = '3.4'          self.accept_encoding = 'gzip' - - -    def subscribe_sync( self, args ) : +    def subscribe_sync(self, args):          """          #**          #* Subscribe @@ -65,50 +64,50 @@ class PubnubCore(PubnubCoreAsync):          pubnub.subscribe({              'channel'  : 'hello_world', -            'callback' : receive  +            'callback' : receive          })          """          ## Fail if missing channel -        if not 'channel' in args : +        if not 'channel' in args:              raise Exception('Missing Channel.')              return False          ## Fail if missing callback -        if not 'callback' in args : +        if not 'callback' in args:              raise Exception('Missing Callback.')              return False          ## Capture User Input -        channel   = str(args['channel']) -        callback  = args['callback'] +        channel = str(args['channel']) +        callback = args['callback']          subscribe_key = args.get('subscribe_key') or self.subscribe_key          ## Begin Subscribe -        while True : +        while True:              timetoken = 'timetoken' in args and args['timetoken'] or 0 -            try : +            try:                  ## Wait for Message -                response = self._request({"urlcomponents" : [ +                response = self._request({"urlcomponents": [                      'subscribe',                      subscribe_key,                      channel,                      '0',                      str(timetoken) -                ],"urlparams" : {"uuid" : self.uuid }}) +                ], "urlparams": {"uuid": self.uuid}}) -                messages          = response[0] +                messages = response[0]                  args['timetoken'] = response[1]                  ## If it was a timeout -                if not len(messages) : +                if not len(messages):                      continue                  ## Run user Callback and Reconnect if user permits. -                for message in messages : -                    if not callback(self.decrypt(message)) : +                for message in messages: +                    if not callback(self.decrypt(message)):                          return              except Exception: diff --git a/common/PubnubCoreAsync.py b/common/PubnubCoreAsync.py index deb6038..de7627f 100644 --- a/common/PubnubCoreAsync.py +++ b/common/PubnubCoreAsync.py @@ -6,32 +6,38 @@ except ImportError:      sha256 = digestmod.new  import hmac +  class EmptyLock():      def __enter__(self):          pass -    def __exit__(self,a,b,c): + +    def __exit__(self, a, b, c):          pass  empty_lock = EmptyLock() +  class PubnubCoreAsync(PubnubBase): -    def start(self): pass  -    def stop(self):  pass +    def start(self): +        pass + +    def stop(self): +        pass      def __init__(          self,          publish_key,          subscribe_key, -        secret_key = False, -        cipher_key = False, -        auth_key = None, -        ssl_on = False, -        origin = 'pubsub.pubnub.com', -        uuid = None, +        secret_key=False, +        cipher_key=False, +        auth_key=None, +        ssl_on=False, +        origin='pubsub.pubnub.com', +        uuid=None,          _tt_lock=empty_lock,          _channel_list_lock=empty_lock -    ) : +    ):          """          #**          #* Pubnub @@ -58,18 +64,18 @@ class PubnubCoreAsync(PubnubBase):              ssl_on=ssl_on,              origin=origin,              UUID=uuid -        )         - -        self.subscriptions              = {} -        self.timetoken                  = 0 -        self.last_timetoken             = 0 -        self.version                    = '3.3.4' -        self.accept_encoding            = 'gzip' -        self.SUB_RECEIVER               = None -        self._connect                   = None -        self._tt_lock                   = _tt_lock -        self._channel_list_lock         = _channel_list_lock -        self._connect                   = lambda: None +        ) + +        self.subscriptions = {} +        self.timetoken = 0 +        self.last_timetoken = 0 +        self.version = '3.3.4' +        self.accept_encoding = 'gzip' +        self.SUB_RECEIVER = None +        self._connect = None +        self._tt_lock = _tt_lock +        self._channel_list_lock = _channel_list_lock +        self._connect = lambda: None      def get_channel_list(self, channels):          channel = '' @@ -101,7 +107,8 @@ class PubnubCoreAsync(PubnubBase):          for i in l:              func(i) -    def subscribe( self, channel, callback, error=None, connect=None, disconnect=None, reconnect=None, sync=False ) : +    def subscribe(self, channel, callback, error=None, +                  connect=None, disconnect=None, reconnect=None, sync=False):          """          #**          #* Subscribe @@ -135,14 +142,15 @@ class PubnubCoreAsync(PubnubBase):          """          with self._tt_lock: -            self.last_timetoken = self.timetoken if self.timetoken != 0 else self.last_timetoken +            self.last_timetoken = self.timetoken if self.timetoken != 0 \ +                else self.last_timetoken              self.timetoken = 0          if sync is True and self.susbcribe_sync is not None:              self.susbcribe_sync(args)              return -        def _invoke(func,msg=None): +        def _invoke(func, msg=None):              if func is not None:                  if msg is not None:                      func(msg) @@ -156,17 +164,17 @@ class PubnubCoreAsync(PubnubBase):                          chobj = self.subscriptions[ch]                          if chobj['connected'] is False:                              chobj['connected'] = True -                            _invoke(chobj['connect'],chobj['name']) +                            _invoke(chobj['connect'], chobj['name'])          def _invoke_error(channel_list=None, err=None):              if channel_list is None:                  for ch in self.subscriptions:                      chobj = self.subscriptions[ch] -                    _invoke(chobj['error'],err) +                    _invoke(chobj['error'], err)              else:                  for ch in channel_list:                      chobj = self.subscriptions[ch] -                    _invoke(chobj['error'],err) +                    _invoke(chobj['error'], err)          def _get_channel():              for ch in self.subscriptions: @@ -174,53 +182,58 @@ class PubnubCoreAsync(PubnubBase):                  if chobj['subscribed'] is True:                      return chobj -          ## New Channel? -        if not channel in self.subscriptions or self.subscriptions[channel]['subscribed'] is False: -            with self._channel_list_lock: -                self.subscriptions[channel] = { -                    'name'          : channel, -                    'first'         : False, -                    'connected'     : False, -                    'subscribed'    : True, -                    'callback'      : callback, -                    'connect'       : connect, -                    'disconnect'    : disconnect, -                    'reconnect'     : reconnect, -                    'error'         : error -                } - +        if not channel in self.subscriptions or \ +                self.subscriptions[channel]['subscribed'] is False: +                with self._channel_list_lock: +                    self.subscriptions[channel] = { +                        'name': channel, +                        'first': False, +                        'connected': False, +                        'subscribed': True, +                        'callback': callback, +                        'connect': connect, +                        'disconnect': disconnect, +                        'reconnect': reconnect, +                        'error': error +                    }          ## return if already connected to channel -        if channel in self.subscriptions and 'connected' in self.subscriptions[channel] and self.subscriptions[channel]['connected'] is True: -            _invoke(error, "Already Connected") -            return -             -             +        if channel in self.subscriptions and \ +            'connected' in self.subscriptions[channel] and \ +                self.subscriptions[channel]['connected'] is True: +                    _invoke(error, "Already Connected") +                    return -        ## SUBSCRIPTION RECURSION  +        ## SUBSCRIPTION RECURSION          def _connect(): -           +              self._reset_offline()              def sub_callback(response):                  ## ERROR ? -                if not response or ('message' in response and response['message'] == 'Forbidden'): -                    _invoke_error(response['payload']['channels'], response['message']) -                    _connect() -                    return +                if not response or \ +                    ('message' in response and +                        response['message'] == 'Forbidden'): +                            _invoke_error(response['payload'][ +                                'channels'], response['message']) +                            _connect() +                            return                  _invoke_connect()                  with self._tt_lock: -                    self.timetoken = self.last_timetoken if self.timetoken == 0 and self.last_timetoken != 0 else response[1] +                    self.timetoken = \ +                        self.last_timetoken if self.timetoken == 0 and \ +                        self.last_timetoken != 0 else response[1]                      if len(response) > 2:                          channel_list = response[2].split(',')                          response_list = response[0]                          for ch in enumerate(channel_list):                              if ch[1] in self.subscriptions:                                  chobj = self.subscriptions[ch[1]] -                                _invoke(chobj['callback'],self.decrypt(response_list[ch[0]])) +                                _invoke(chobj['callback'], +                                        self.decrypt(response_list[ch[0]]))                      else:                          response_list = response[0]                          chobj = _get_channel() @@ -230,23 +243,25 @@ class PubnubCoreAsync(PubnubBase):                      _connect() -              channel_list = self.get_channel_list(self.subscriptions)              if len(channel_list) <= 0:                  return              ## CONNECT TO PUBNUB SUBSCRIBE SERVERS              try: -                self.SUB_RECEIVER = self._request( { "urlcomponents" : [ +                self.SUB_RECEIVER = self._request({"urlcomponents": [                      'subscribe',                      self.subscribe_key,                      channel_list,                      '0',                      str(self.timetoken) -                ], "urlparams" : {"uuid":self.uuid, "auth" : self.auth_key} }, sub_callback, sub_callback, single=True ) +                ], "urlparams": {"uuid": self.uuid, "auth": self.auth_key}}, +                    sub_callback, +                    sub_callback, +                    single=True)              except Exception as e:                  print(e) -                self.timeout( 1, _connect) +                self.timeout(1, _connect)                  return          self._connect = _connect @@ -263,8 +278,7 @@ class PubnubCoreAsync(PubnubBase):          self._reset_offline()          self._connect() - -    def unsubscribe( self, channel ): +    def unsubscribe(self, channel):          if channel in self.subscriptions is False:              return False @@ -272,8 +286,8 @@ class PubnubCoreAsync(PubnubBase):          ## DISCONNECT          with self._channel_list_lock:              if channel in self.subscriptions: -                self.subscriptions[channel]['connected']    = 0 -                self.subscriptions[channel]['subscribed']   = False -                self.subscriptions[channel]['timetoken']    = 0 -                self.subscriptions[channel]['first']        = False +                self.subscriptions[channel]['connected'] = 0 +                self.subscriptions[channel]['subscribed'] = False +                self.subscriptions[channel]['timetoken'] = 0 +                self.subscriptions[channel]['first'] = False          self.CONNECT() diff --git a/common/PubnubCrypto.py b/common/PubnubCrypto.py index 3489216..295a76e 100644 --- a/common/PubnubCrypto.py +++ b/common/PubnubCrypto.py @@ -1,10 +1,11 @@  from Crypto.Cipher import AES  from Crypto.Hash import MD5 -from base64 import encodestring, decodestring  +from base64 import encodestring, decodestring  import hashlib  import hmac -class PubnubCrypto2() : + +class PubnubCrypto2():      """      #**      #* PubnubCrypto @@ -15,8 +16,8 @@ class PubnubCrypto2() :      pc = PubnubCrypto      """ -    -    def pad( self, msg, block_size=16 ): + +    def pad(self, msg, block_size=16):          """          #**          #* pad @@ -28,9 +29,9 @@ class PubnubCrypto2() :          #**          """          padding = block_size - (len(msg) % block_size) -        return msg + chr(padding)*padding -        -    def depad( self, msg ): +        return msg + chr(padding) * padding + +    def depad(self, msg):          """          #**          #* depad @@ -41,7 +42,7 @@ class PubnubCrypto2() :          """          return msg[0:-ord(msg[-1])] -    def getSecret( self, key ): +    def getSecret(self, key):          """          #**          #* getSecret @@ -52,7 +53,7 @@ class PubnubCrypto2() :          """          return hashlib.sha256(key).hexdigest() -    def encrypt( self, key, msg ): +    def encrypt(self, key, msg):          """          #**          #* encrypt @@ -62,11 +63,12 @@ class PubnubCrypto2() :          #**          """          secret = self.getSecret(key) -        Initial16bytes='0123456789012345' -        cipher = AES.new(secret[0:32],AES.MODE_CBC,Initial16bytes) +        Initial16bytes = '0123456789012345' +        cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)          enc = encodestring(cipher.encrypt(self.pad(msg)))          return enc -    def decrypt( self, key, msg ): + +    def decrypt(self, key, msg):          """          #**          #* decrypt @@ -76,12 +78,12 @@ class PubnubCrypto2() :          #**          """          secret = self.getSecret(key) -        Initial16bytes='0123456789012345' -        cipher = AES.new(secret[0:32],AES.MODE_CBC,Initial16bytes) +        Initial16bytes = '0123456789012345' +        cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)          return self.depad((cipher.decrypt(decodestring(msg)))) -class PubnubCrypto3() : +class PubnubCrypto3():      """      #**      #* PubnubCrypto @@ -92,8 +94,8 @@ class PubnubCrypto3() :      pc = PubnubCrypto      """ -    -    def pad( self, msg, block_size=16 ): + +    def pad(self, msg, block_size=16):          """          #**          #* pad @@ -105,9 +107,9 @@ class PubnubCrypto3() :          #**          """          padding = block_size - (len(msg) % block_size) -        return msg + (chr(padding)*padding).encode('utf-8') -        -    def depad( self, msg ): +        return msg + (chr(padding) * padding).encode('utf-8') + +    def depad(self, msg):          """          #**          #* depad @@ -118,7 +120,7 @@ class PubnubCrypto3() :          """          return msg[0:-ord(msg[-1])] -    def getSecret( self, key ): +    def getSecret(self, key):          """          #**          #* getSecret @@ -129,7 +131,7 @@ class PubnubCrypto3() :          """          return hashlib.sha256(key.encode("utf-8")).hexdigest() -    def encrypt( self, key, msg ): +    def encrypt(self, key, msg):          """          #**          #* encrypt @@ -139,10 +141,12 @@ class PubnubCrypto3() :          #**          """          secret = self.getSecret(key) -        Initial16bytes='0123456789012345' -        cipher = AES.new(secret[0:32],AES.MODE_CBC,Initial16bytes) -        return encodestring(cipher.encrypt(self.pad(msg.encode('utf-8')))).decode('utf-8') -    def decrypt( self, key, msg ): +        Initial16bytes = '0123456789012345' +        cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes) +        return encodestring( +            cipher.encrypt(self.pad(msg.encode('utf-8')))).decode('utf-8') + +    def decrypt(self, key, msg):          """          #**          #* decrypt @@ -152,6 +156,7 @@ class PubnubCrypto3() :          #**          """          secret = self.getSecret(key) -        Initial16bytes='0123456789012345' -        cipher = AES.new(secret[0:32],AES.MODE_CBC,Initial16bytes) -        return (cipher.decrypt(decodestring(msg.encode('utf-8')))).decode('utf-8') +        Initial16bytes = '0123456789012345' +        cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes) +        return (cipher.decrypt( +            decodestring(msg.encode('utf-8')))).decode('utf-8') diff --git a/common/PubnubUnitTest.py b/common/PubnubUnitTest.py index 2f9d28c..518d226 100644 --- a/common/PubnubUnitTest.py +++ b/common/PubnubUnitTest.py @@ -1,36 +1,37 @@  import time +  class Suite(): -	def __init__(self, pubnub, expected): -		self.pubnub = pubnub -		self.total = expected -		self.passed = 0 -		self.failed = 0 -		self.started = False +    def __init__(self, pubnub, expected): +        self.pubnub = pubnub +        self.total = expected +        self.passed = 0 +        self.failed = 0 +        self.started = False -	def test(self, condition , name, message = None, response = None): +    def test(self, condition, name, message=None, response=None): -		if condition: -			self.passed += 1 -			msg = "PASS : " + name -			if message: -				msg += ", " + message -			if response: -				msg += ", " + response -			print msg -		else: -			self.failed += 1 -			msg = "FAIL : " + name -			if message: -				msg += ", " + message -			if response: -				msg += ", " + response -			print msg +        if condition: +            self.passed += 1 +            msg = "PASS : " + name +            if message: +                msg += ", " + message +            if response: +                msg += ", " + response +            print msg +        else: +            self.failed += 1 +            msg = "FAIL : " + name +            if message: +                msg += ", " + message +            if response: +                msg += ", " + response +            print msg -		if self.total == self.failed + self.passed: -			print "\n======== RESULT ========" -			print "Total\t:\t", self.total -			print "Passed\t:\t", self.passed -			print "Failed\t:\t", self.failed -			self.pubnub.stop() +        if self.total == self.failed + self.passed: +            print "\n======== RESULT ========" +            print "Total\t:\t", self.total +            print "Passed\t:\t", self.passed +            print "Failed\t:\t", self.failed +            self.pubnub.stop() diff --git a/common/unit-test-async.py b/common/unit-test-async.py index f95c759..8123fdb 100644 --- a/common/unit-test-async.py +++ b/common/unit-test-async.py @@ -1,4 +1,4 @@ -## www.pubnub.com - PubNub Real-time push service in the cloud.  +## www.pubnub.com - PubNub Real-time push service in the cloud.  # coding=utf8  ## PubNub Real-time Push APIs and Notifications Framework @@ -17,42 +17,45 @@ sys.path.append('./')  sys.path.append('../common/')  from Pubnub import Pubnub -publish_key   = len(sys.argv) > 1 and sys.argv[1] or 'demo' +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'  subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' -secret_key    = len(sys.argv) > 3 and sys.argv[3] or None  -cipher_key    = len(sys.argv) > 4 and sys.argv[4] or None -ssl_on        = len(sys.argv) > 5 and bool(sys.argv[5]) or False +secret_key = len(sys.argv) > 3 and sys.argv[3] or None +cipher_key = len(sys.argv) > 4 and sys.argv[4] or None +ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False  ## -----------------------------------------------------------------------  ## Initiat Class  ## ----------------------------------------------------------------------- -pubnub = Pubnub( publish_key, subscribe_key, secret_key, cipher_key, ssl_on ) +pubnub = Pubnub(publish_key, subscribe_key, secret_key, cipher_key, ssl_on)  ch = 'python-async-test-channel-'  expect = 0  done = 0  failures = 0  passes = 0 +  def stop():      global done      global count      pubnub.stop()      print "============================" -    print 'Total\t:\t' , failures + passes -    print 'PASS\t:\t' , passes +    print 'Total\t:\t', failures + passes +    print 'PASS\t:\t', passes      print 'FAIL\t:\t', failures      print "============================"  ## ---------------------------------------------------------------------------  ## Unit Test Function  ## --------------------------------------------------------------------------- -def test( trial, name ) : + + +def test(trial, name):      global failures      global passes      global done      done += 1      #print trial -    if trial == False: +    if trial is False:          print 'FAIL : ', name          failures += 1      else: @@ -61,77 +64,87 @@ def test( trial, name ) :      if done == expect:          stop() +  def test_publish():      channel = ch + str(random.random()) +      def publish_cb(messages):          test(messages[0] == 1, "Publish Test")      pubnub.publish({ -        'channel' : channel, -        'message' :  {'one': 'Hello World! --> ɂ顶@#$%^&*()!', 'two': 'hello2'}, -        'callback' : publish_cb -    })  +        'channel': channel, +        'message': {'one': 'Hello World! --> ɂ顶@#$%^&*()!', 'two': 'hello2'}, +        'callback': publish_cb +    })  def test_history():      channel = ch + str(random.random()) +      def history_cb(messages): -        test(len(messages) <= 1, "History Test")     +        test(len(messages) <= 1, "History Test")      pubnub.history({ -        'channel' : channel, -        'limit' :  1, -        'callback' : history_cb  +        'channel': channel, +        'limit': 1, +        'callback': history_cb      }) -  def test_subscribe():      message = "Testing Subscribe " + str(random.random())      channel = ch + str(random.random()) +      def subscribe_connect_cb():          def publish_cb(response): -            test(response[0] == 1, 'Publish Test in subscribe Connect Callback') +            test(response[0] == 1, +                 'Publish Test in subscribe Connect Callback')          pubnub.publish({ -            'channel'  :  channel, -            'message'  :  message, -            'callback' : publish_cb +            'channel': channel, +            'message': message, +            'callback': publish_cb          }) +      def subscribe_cb(response): -        test(response == message , 'Subscribe Receive Test in subscribe Callback') +        test(response == message, +             'Subscribe Receive Test in subscribe Callback')      pubnub.subscribe({ -        'channel' : channel, -        'connect' : subscribe_connect_cb, +        'channel': channel, +        'connect': subscribe_connect_cb,          'callback': subscribe_cb -    })  -     +    }) +  def test_here_now(): -    channel = ch + str(random.random())  +    channel = ch + str(random.random())      message = "Testing Subscribe" +      def subscribe_connect_cb():          def here_now_cb(response):              test(response["occupancy"] > 0, 'Here Now Test') +              def publish_cb(response): -                test(response[0] == 1, 'Here Now Test: Publish Test in subscribe Connect Callback') +                test(response[0] == 1, +                     'Here Now Test: Publish Test in \ +                            subscribe Connect Callback')              pubnub.publish({ -                'channel'  : channel, -                'message'  : message, -                'callback' : publish_cb +                'channel': channel, +                'message': message, +                'callback': publish_cb              })          time.sleep(5)          pubnub.here_now({ -            'channel' : channel, -            'callback' : here_now_cb +            'channel': channel, +            'callback': here_now_cb          }) -      def subscribe_cb(response): -        test(response == message , 'Here Now Test: Subscribe Receive Test in subscribe Callback') +        test(response == message, +             'Here Now Test: Subscribe Receive Test in subscribe Callback')      pubnub.subscribe({ -        'channel' : channel, -        'connect' : subscribe_connect_cb, +        'channel': channel, +        'connect': subscribe_connect_cb,          'callback': subscribe_cb -    })  +    })  expect = 7  test_publish() @@ -140,7 +153,6 @@ test_subscribe()  test_here_now() -  pubnub.start()  if failures > 0:      raise Exception('Fail', failures) | 
