diff options
Diffstat (limited to 'PubnubCoreAsync.py')
| -rw-r--r-- | PubnubCoreAsync.py | 255 | 
1 files changed, 20 insertions, 235 deletions
| diff --git a/PubnubCoreAsync.py b/PubnubCoreAsync.py index b31fdfe..9c53c6e 100644 --- a/PubnubCoreAsync.py +++ b/PubnubCoreAsync.py @@ -22,8 +22,9 @@ except ImportError:      sha256 = digestmod.new  import hmac  from PubnubCrypto import PubnubCrypto +from PubnubBase import PubnubBase -class PubnubCoreAsync(object): +class PubnubCoreAsync(PubnubBase):      def start(self): pass       def stop(self):  pass @@ -57,112 +58,20 @@ class PubnubCoreAsync(object):          pubnub = Pubnub( 'PUBLISH-KEY', 'SUBSCRIBE-KEY', 'SECRET-KEY', False )          """ -        self.origin        = origin -        self.publish_key   = publish_key -        self.subscribe_key = subscribe_key -        self.secret_key    = secret_key -        self.cipher_key    = cipher_key -        self.ssl           = ssl_on +        super(PubnubCoreAsync, self).__init__( +            publish_key=publish_key, +            subscribe_key=subscribe_key, +            secret_key=secret_key, +            cipher_key=cipher_key, +            ssl_on=ssl_on, +            origin=origin, +            UUID=uuid +        )         +          self.subscriptions = {}          self.timetoken     = 0 -        self.uuid          = uuid or str(self.uuid())           self.version       = '3.4'          self.accept_encoding = 'gzip' -        print self.ssl -        if self.ssl : -            self.origin = 'https://' + self.origin -        else : -            self.origin = 'http://'  + self.origin - - -    def publish( self, args ) : -        """ -        #** -        #* Publish -        #* -        #* Send a message to a channel. -        #* -        #* @param array args with channel and message. -        #* @return array success information. -        #** - -        ## Publish Example -        def publish_complete(info): -            print(info) - -        pubnub.publish({ -            'channel' : 'hello_world', -            'message' : { -                'some_text' : 'Hello my World' -            }, -            'callback' : publish_complete -        }) - -        """ -        ## Capture Callback -        if args.has_key('callback'): callback = args['callback'] -        else: callback = lambda x : x - -        ## Fail if bad input. -        if not (args['channel'] and args['message']): -            callback([ 0, 'Missing Channel or Message', 0 ]) -            return False - -        ## Capture User Input -        channel = str(args['channel']) -        message = args['message'] - -        if self.cipher_key : -            pc = PubnubCrypto() -            out = [] -            if type( message ) == type(list()): -                for item in message: -                    encryptItem = pc.encrypt(self.cipher_key, item ).rstrip() -                    out.append(encryptItem) -                message = json.dumps(out) -            elif type( message ) == type(dict()): -                outdict = {} -                for k, item in message.iteritems(): -                    encryptItem = pc.encrypt(self.cipher_key, item ).rstrip() -                    outdict[k] = encryptItem -                    out.append(outdict) -                message = json.dumps(out[0]) -            else: -                message = json.dumps(pc.encrypt(self.cipher_key, message).replace('\n','')) -        else : -            message = json.dumps(args['message']) - -        def publish_response(info): -            callback(info or [0, 'Disconnected', 0]); - -        ## Sign Message -        if self.secret_key : -            hashObject = sha256() -            hashObject.update(self.secret_key) -            hashedSecret = hashObject.hexdigest() -            hash = hmac.HMAC(hashedSecret, '/'.join([ -                    self.publish_key, -                    self.subscribe_key, -                    self.secret_key, -                    channel, -                    message -                ]), digestmod=digestmod) -            signature = hash.hexdigest()         -        else : -            signature = '0' - -        ## Send Message -        return self._request({ "urlcomponents" : [ -            'publish', -            self.publish_key, -            self.subscribe_key, -            signature, -            channel, -            '0', -            message -        ] }, publish_response ) - -      def subscribe( self, args ) :          """ @@ -227,7 +136,7 @@ class PubnubCoreAsync(object):          self.subscriptions[channel]['connected'] = 1          ## SUBSCRIPTION RECURSION  -        def substabizel(): +        def _subscribe():              ## STOP CONNECTION?              if not self.subscriptions[channel]['connected']:                  return @@ -248,43 +157,24 @@ class PubnubCoreAsync(object):                  if not response:                      def time_callback(_time):                          if not _time: -                            self.timeout( 1, substabizel ) +                            self.timeout( 1, _subscribe )                              return errorback("Lost Network Connection")                          else: -                            self.timeout( 1, substabizel ) +                            self.timeout( 1, _subscribe)                      ## ENSURE CONNECTED (Call Time Function)                      return self.time({ 'callback' : time_callback })                  self.timetoken = response[1] -                substabizel() +                _subscribe()                  pc = PubnubCrypto()                  out = []                  for message in response[0]: -                     print type(message) -                     if self.cipher_key : -                          if type( message ) == type(list()): -                              for item in message: -                                  encryptItem = pc.decrypt(self.cipher_key, item ) -                                  out.append(encryptItem) -                              message = out -                          elif type( message ) == type(dict()): -                              outdict = {} -                              for k, item in message.iteritems(): -                                  encryptItem = pc.decrypt(self.cipher_key, item ) -                                  outdict[k] = encryptItem -                                  out.append(outdict) -                              message = out[0] -                          else: -                              message = pc.decrypt(self.cipher_key, message ) -                     else : -                          message - -                     callback(message) +                     callback(self.decrypt(message))              ## CONNECT TO PUBNUB SUBSCRIBE SERVERS -            try : +            try:                  self._request( { "urlcomponents" : [                      'subscribe',                      self.subscribe_key, @@ -293,113 +183,8 @@ class PubnubCoreAsync(object):                      str(self.timetoken)                  ], "urlparams" : {"uuid":self.uuid} }, sub_callback )              except : -                self.timeout( 1, substabizel ) +                self.timeout( 1, _subscribe)                  return          ## BEGIN SUBSCRIPTION (LISTEN FOR MESSAGES) -        substabizel() - - -    def unsubscribe( self, args ): -        channel = str(args['channel']) -        if not (channel in self.subscriptions): -            return False - -        ## DISCONNECT -        self.subscriptions[channel]['connected'] = 0 -        self.subscriptions[channel]['timetoken'] = 0 -        self.subscriptions[channel]['first']     = False - - -    def history( self, args ) : -        """ -        #** -        #* History -        #* -        #* Load history from a channel. -        #* -        #* @param array args with 'channel' and 'limit'. -        #* @return mixed false on fail, array on success. -        #* - -        ## History Example -        history = pubnub.history({ -            'channel' : 'hello_world', -            'limit'   : 1 -        }) -        print(history) - -        """ -        ## Capture User Input -        limit   = args.has_key('limit') and int(args['limit']) or 10 -        channel = str(args['channel']) - -        ## Fail if bad input. -        if not channel : -            return 'Missing Channel' - -        ## Get History -        pc = PubnubCrypto() -        return self._request( {"urlcomponents" : [ -            'history', -            self.subscribe_key, -            channel, -            '0', -            str(limit) -        ]}, args['callback'] ) - -    def time( self, args ) : -        """ -        #** -        #* Time -        #* -        #* Timestamp from PubNub Cloud. -        #* -        #* @return int timestamp. -        #* - -        ## PubNub Server Time Example -        def time_complete(timestamp): -            print(timestamp) - -        pubnub.time(time_complete) - -        """ -        def complete(response) : -            if not response: return 0 -            args['callback'](response[0]) - -        self._request( { "urlcomponents" : [ -            'time', -            '0' -        ]}, complete ) - -    def uuid(self) : -        """ -        #** -        #* uuid -        #* -        #* Generate a UUID -        #* -        #* @return  UUID. -        #* - -        ## PubNub UUID Example -        uuid = pubnub.uuid() -        print(uuid) -        """ -        return uuid.uuid1() - -    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"]]) -        if (request.has_key("urlparams")): -            url = url + '?' + "&".join([ x + "=" + y  for x,y in request["urlparams"].items()]) -        return url - -    def _request( self, request, callback, timeout=30 ) : -        pass +        _subscribe() | 
