From 765ee5db6fc39d77e55dcf4fe97fb96da2f46d30 Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 2 Apr 2014 02:44:29 +0530 Subject: multiplexing support --- python-tornado/Pubnub.py | 329 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 247 insertions(+), 82 deletions(-) (limited to 'python-tornado/Pubnub.py') diff --git a/python-tornado/Pubnub.py b/python-tornado/Pubnub.py index 89c0d97..ee66619 100644 --- a/python-tornado/Pubnub.py +++ b/python-tornado/Pubnub.py @@ -16,7 +16,7 @@ from base64 import encodestring, decodestring import hashlib import hmac -class PubnubCrypto() : +class PubnubCrypto2() : """ #** #* PubnubCrypto @@ -93,13 +93,89 @@ class PubnubCrypto() : return self.depad((cipher.decrypt(decodestring(msg)))) +class PubnubCrypto3() : + """ + #** + #* PubnubCrypto + #* + #** + + ## Initiate Class + pc = PubnubCrypto + + """ + + def pad( self, msg, block_size=16 ): + """ + #** + #* pad + #* + #* pad the text to be encrypted + #* appends a padding character to the end of the String + #* until the string has block_size length + #* @return msg with padding. + #** + """ + padding = block_size - (len(msg) % block_size) + return msg + (chr(padding)*padding).encode('utf-8') + + def depad( self, msg ): + """ + #** + #* depad + #* + #* depad the decryptet message" + #* @return msg without padding. + #** + """ + return msg[0:-ord(msg[-1])] + + def getSecret( self, key ): + """ + #** + #* getSecret + #* + #* hases the key to MD5 + #* @return key in MD5 format + #** + """ + return hashlib.sha256(key.encode("utf-8")).hexdigest() + + def encrypt( self, key, msg ): + """ + #** + #* encrypt + #* + #* encrypts the message + #* @return message in encrypted format + #** + """ + 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 ): + """ + #** + #* decrypt + #* + #* decrypts the message + #* @return message in decryped format + #** + """ + 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') + + try: import json except ImportError: import simplejson as json import time import hashlib -import urllib2 -import uuid +import uuid +import sys class PubnubBase(object): def __init__( @@ -137,7 +213,7 @@ class PubnubBase(object): self.secret_key = secret_key self.cipher_key = cipher_key self.ssl = ssl_on - self.pc = PubnubCrypto() + if self.ssl : self.origin = 'https://' + self.origin @@ -145,8 +221,16 @@ class PubnubBase(object): 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() + else: + self.python_version = 3 + self.pc = PubnubCrypto3() + - if not isinstance(self.uuid, basestring): + if not isinstance(self.uuid, str): raise AttributeError("pres_uuid must be a string") def sign(self, channel, message): @@ -177,6 +261,14 @@ class PubnubBase(object): return message + 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']}) + else: + if (callback != None):callback(response) + if (callback != None): return _new_format_callback + def publish( self, args ) : """ @@ -207,7 +299,7 @@ class PubnubBase(object): channel = str(args['channel']) ## Capture Callback - if args.has_key('callback') : + if 'callback' in args : callback = args['callback'] else : callback = None @@ -226,7 +318,7 @@ class PubnubBase(object): channel, '0', message - ]}, callback) + ]'urlparams' : {'auth' : self.auth_key}}, self._return_wrapped_callback(callback)) def presence( self, args ) : """ @@ -266,7 +358,7 @@ class PubnubBase(object): callback = args['callback'] subscribe_key = args.get('subscribe_key') or self.subscribe_key - return self.subscribe({'channel': channel+'-pnpres', 'subscribe_key':subscribe_key, 'callback': callback}) + return self.subscribe({'channel': channel+'-pnpres', 'subscribe_key':subscribe_key, 'callback': self._return_wrapped_callback(callback)}) def here_now( self, args ) : @@ -291,7 +383,7 @@ class PubnubBase(object): channel = str(args['channel']) ## Capture Callback - if args.has_key('callback') : + if 'callback' in args : callback = args['callback'] else : callback = None @@ -329,7 +421,7 @@ class PubnubBase(object): """ ## Capture User Input - limit = args.has_key('limit') and int(args['limit']) or 10 + limit = 'limit' in args and int(args['limit']) or 10 channel = str(args['channel']) ## Fail if bad input. @@ -338,7 +430,7 @@ class PubnubBase(object): return False ## Capture Callback - if args.has_key('callback') : + if 'callback' in args : callback = args['callback'] else : callback = None @@ -377,18 +469,18 @@ class PubnubBase(object): params = dict() count = 100 - if args.has_key('count'): + if 'count' in args: count = int(args['count']) params['count'] = str(count) - if args.has_key('reverse'): + if 'reverse' in args: params['reverse'] = str(args['reverse']).lower() - if args.has_key('start'): + if 'start' in args: params['start'] = str(args['start']) - if args.has_key('end'): + if 'end' in args: params['end'] = str(args['end']) ## Fail if bad input. @@ -397,7 +489,7 @@ class PubnubBase(object): return False ## Capture Callback - if args.has_key('callback') : + if 'callback' in args : callback = args['callback'] else : callback = None @@ -428,7 +520,7 @@ class PubnubBase(object): """ ## Capture Callback - if args and args.has_key('callback') : + if args and 'callback' in args : callback = args['callback'] else : callback = None @@ -454,8 +546,8 @@ class PubnubBase(object): 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"].iteritems()]) + if ("urlparams" in request): + url = url + '?' + "&".join([ x + "=" + y for x,y in request["urlparams"].items()]) return url @@ -471,8 +563,6 @@ class PubnubCoreAsync(PubnubBase): def start(self): pass def stop(self): pass - def timeout( self, delay, callback ): - pass def __init__( self, @@ -515,8 +605,23 @@ class PubnubCoreAsync(PubnubBase): self.timetoken = 0 self.version = '3.3.4' self.accept_encoding = 'gzip' - - def subscribe( self, args ) : + self.SUB_RECEIVER = None + self._connect = None + + def get_channel_list(self, channels): + channel = '' + first = True + for ch in channels: + if not channels[ch]['subscribed']: + continue + if not first: + channel += ',' + else: + first = False + channel += ch + return channel + + def subscribe( self, args=None, sync=False ) : """ #** #* Subscribe @@ -548,97 +653,143 @@ class PubnubCoreAsync(PubnubBase): }) """ - ## Fail if missing channel - if not 'channel' in args : - return 'Missing Channel.' - ## Fail if missing callback - if not 'callback' in args : - return 'Missing Callback.' + if sync is True and self.susbcribe_sync is not None: + self.susbcribe_sync(args) + return - ## Capture User Input - channel = str(args['channel']) - callback = args['callback'] - connectcb = args['connect'] + def _invoke(func,msg=None): + if func is not None: + if msg is not None: + func(msg) + else: + func() + + def _invoke_connect(): + for ch in self.subscriptions: + chobj = self.subscriptions[ch] + if chobj['connected'] is False: + chobj['connected'] = True + _invoke(chobj['connect']) + + def _invoke_error(err=None): + for ch in self.subscriptions: + chobj = self.subscriptions[ch] + _invoke(chobj.error,err) + + + if callback is None: + _invoke(error, "Callback Missing") + return + + if channel is None: + _invoke(error, "Channel Missing") + return + + def _get_channel(): + for ch in self.subscriptions: + chobj = self.subscriptions[ch] + if chobj['subscribed'] is True: + return chobj - if 'errorback' in args: - errorback = args['errorback'] - else: - errorback = lambda x: x ## New Channel? - if not (channel in self.subscriptions) : + if not channel in self.subscriptions: self.subscriptions[channel] = { - 'first' : False, - 'connected' : False, + 'name' : channel, + 'first' : False, + 'connected' : False, + 'subscribed' : True, + 'callback' : callback, + 'connect' : connect, + 'disconnect' : disconnect, + 'reconnect' : reconnect } - ## Ensure Single Connection + ## return if already connected to channel if self.subscriptions[channel]['connected'] : - return "Already Connected" + _invoke(error, "Already Connected") + return + - self.subscriptions[channel]['connected'] = 1 ## SUBSCRIPTION RECURSION - def _subscribe(): - ## STOP CONNECTION? - if not self.subscriptions[channel]['connected']: - return + def _connect(): + self._reset_offline() + def sub_callback(response): - if not self.subscriptions[channel]['first'] : - self.subscriptions[channel]['first'] = True - connectcb() + print response + ## ERROR ? + if not response or error in response: + _invoke_error() - ## STOP CONNECTION? - if not self.subscriptions[channel]['connected']: - return + _invoke_connect() + self.timetoken = response[1] - ## PROBLEM? - if not response: - def time_callback(_time): - if not _time: - self.timeout( 1, _subscribe ) - return errorback("Lost Network Connection") - else: - self.timeout( 1, _subscribe) + 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]])) + else: + response_list = response[0] + chobj = _get_channel() + for r in response_list: + if chobj: + _invoke(chobj['callback'], self.decrypt(r)) - ## ENSURE CONNECTED (Call Time Function) - return self.time({ 'callback' : time_callback }) - self.timetoken = response[1] - _subscribe() + _connect() + - pc = PubnubCrypto() - out = [] - for message in response[0]: - callback(self.decrypt(message)) + channel_list = self.get_channel_list(self.subscriptions) + print channel_list ## CONNECT TO PUBNUB SUBSCRIBE SERVERS try: - self._request( { "urlcomponents" : [ + self.SUB_RECEIVER = self._request( { "urlcomponents" : [ 'subscribe', self.subscribe_key, - channel, + channel_list, '0', str(self.timetoken) - ], "urlparams" : {"uuid":self.uuid} }, sub_callback ) - except : - self.timeout( 1, _subscribe) + ], "urlparams" : {"uuid":self.uuid} }, sub_callback, single=True ) + except Exception as e: + self.timeout( 1, _connect) return + self._connect = _connect + + ## BEGIN SUBSCRIPTION (LISTEN FOR MESSAGES) - _subscribe() + _connect() + + def _reset_offline(self): + if self.SUB_RECEIVER is not None: + self.SUB_RECEIVER() + self.SUB_RECEIVER = None + + def CONNECT(self): + self._reset_offline() + self._connect() + + def unsubscribe( self, args ): + #print(args['channel']) channel = str(args['channel']) if not (channel in self.subscriptions): return False ## DISCONNECT self.subscriptions[channel]['connected'] = 0 + self.subscriptions[channel]['subscribed'] = False self.subscriptions[channel]['timetoken'] = 0 self.subscriptions[channel]['first'] = False + self.CONNECT() import tornado.httpclient @@ -685,15 +836,24 @@ class Pubnub(PubnubCoreAsync): self.headers['Accept-Encoding'] = self.accept_encoding self.headers['V'] = self.version self.http = tornado.httpclient.AsyncHTTPClient(max_clients=1000) + self.id = None - def _request( self, request, callback ) : + def _request( self, request, callback, single=False ) : url = self.getUrl(request) - ## Send Request Expecting JSON Response - #print self.headers - request = tornado.httpclient.HTTPRequest( url, 'GET', self.headers, connect_timeout=10, request_timeout=310 ) + if single is True: + id = time.time() + self.id = id def responseCallback(response): + if single is True: + if not id == self.id: + return None + + body = response._get_body() + if body is None: + return + def handle_exc(*args): return True if response.error is not None: @@ -701,9 +861,14 @@ class Pubnub(PubnubCoreAsync): response.rethrow() elif callback: callback(eval(response._get_body())) - + self.http.fetch( - request, - callback=responseCallback, + request=request, + callback=responseCallback ) + def abort(): + pass + + return abort + -- cgit v1.2.3 From 99096b8c11b9a541f6350639e8735495cf90091c Mon Sep 17 00:00:00 2001 From: Devendra Date: Fri, 11 Apr 2014 14:49:43 +0530 Subject: v1 MX and async code for python, twisted, tornado --- python-tornado/Pubnub.py | 246 +++++++++++++++++++++++++++++++++++++---------- 1 file changed, 197 insertions(+), 49 deletions(-) (limited to 'python-tornado/Pubnub.py') diff --git a/python-tornado/Pubnub.py b/python-tornado/Pubnub.py index ee66619..61f7c3d 100644 --- a/python-tornado/Pubnub.py +++ b/python-tornado/Pubnub.py @@ -176,6 +176,14 @@ import time import hashlib import uuid import sys +from urllib import quote + +from base64 import urlsafe_b64encode +from hashlib import sha256 +from urllib import quote +from urllib import urlopen + +import hmac class PubnubBase(object): def __init__( @@ -184,6 +192,7 @@ class PubnubBase(object): subscribe_key, secret_key = False, cipher_key = False, + auth_key = None, ssl_on = False, origin = 'pubsub.pubnub.com', UUID = None @@ -213,6 +222,7 @@ class PubnubBase(object): self.secret_key = secret_key self.cipher_key = cipher_key self.ssl = ssl_on + self.auth_key = auth_key if self.ssl : @@ -247,6 +257,86 @@ class PubnubBase(object): signature = '0' return signature + def _pam_sign( self, msg ): + """Calculate a signature by secret key and message.""" + + return urlsafe_b64encode(hmac.new( + self.secret_key.encode("utf-8"), + msg.encode("utf-8"), + sha256 + ).digest()) + + def _pam_auth( self, query , apicode=0, callback=None): + """Issue an authenticated request.""" + + if 'timestamp' not in query: + query['timestamp'] = int(time.time()) + + ## Global Grant? + if 'auth' in query and not query['auth']: + del query['auth'] + + if 'channel' in query and not query['channel']: + del query['channel'] + + params = "&".join([ + x + "=" + quote( + str(query[x]), safe="" + ) for x in sorted(query) + ]) + sign_input = "{subkey}\n{pubkey}\n{apitype}\n{params}".format( + subkey=self.subscribe_key, + pubkey=self.publish_key, + apitype="audit" if (apicode) else "grant", + params=params + ) + + 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" , + 'sub-key', + self.subscribe_key + ], 'urlparams' : {'auth' : self.auth_key, 'signature' : signature}}, + self._return_wrapped_callback(callback)) + + 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 + }, callback=callback) + + def revoke( self, channel, authkey=False, read=False, write=False, ttl=1, callback=None): + """Revoke 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 + }, callback=callback) + + def audit(self, channel=False, authkey=False, callback=None): + return self._pam_auth({ + "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','')) @@ -318,7 +408,7 @@ class PubnubBase(object): channel, '0', message - ]'urlparams' : {'auth' : self.auth_key}}, self._return_wrapped_callback(callback)) + ], 'urlparams' : {'auth' : self.auth_key}}, self._return_wrapped_callback(callback)) def presence( self, args ) : """ @@ -520,7 +610,7 @@ class PubnubBase(object): """ ## Capture Callback - if args and 'callback' in args : + if args and 'callback' in args: callback = args['callback'] else : callback = None @@ -547,7 +637,7 @@ class PubnubBase(object): ch for ch in list(bit) ]) for bit in request["urlcomponents"]]) if ("urlparams" in request): - url = url + '?' + "&".join([ x + "=" + y for x,y in request["urlparams"].items()]) + url = url + '?' + "&".join([ x + "=" + str(y) for x,y in request["urlparams"].items()]) return url @@ -558,6 +648,9 @@ except ImportError: import Crypto.Hash.SHA256 as digestmod sha256 = digestmod.new import hmac +import threading +from threading import current_thread +import threading class PubnubCoreAsync(PubnubBase): @@ -570,6 +663,7 @@ class PubnubCoreAsync(PubnubBase): subscribe_key, secret_key = False, cipher_key = False, + auth_key = None, ssl_on = False, origin = 'pubsub.pubnub.com', uuid = None @@ -596,6 +690,7 @@ class PubnubCoreAsync(PubnubBase): subscribe_key=subscribe_key, secret_key=secret_key, cipher_key=cipher_key, + auth_key=auth_key, ssl_on=ssl_on, origin=origin, UUID=uuid @@ -603,22 +698,36 @@ class PubnubCoreAsync(PubnubBase): 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 = threading.RLock() def get_channel_list(self, channels): channel = '' first = True - for ch in channels: - if not channels[ch]['subscribed']: - continue - if not first: - channel += ',' - else: - first = False - channel += ch + if self._channel_list_lock: + with self._channel_list_lock: + for ch in channels: + if not channels[ch]['subscribed']: + continue + if not first: + channel += ',' + else: + first = False + channel += ch + else: + for ch in channels: + if not channels[ch]['subscribed']: + continue + if not first: + channel += ',' + else: + first = False + channel += ch + return channel def subscribe( self, args=None, sync=False ) : @@ -653,6 +762,26 @@ class PubnubCoreAsync(PubnubBase): }) """ + if args is None: + _invoke(error, "Arguments Missing") + return + channel = args['channel'] if 'channel' in args else None + callback = args['callback'] if 'callback' in args else None + connect = args['connect'] if 'connect' in args else None + disconnect = args['disconnect'] if 'disconnect' in args else None + reconnect = args['reconnect'] if 'reconnect' in args else None + error = args['error'] if 'error' in args else None + + with self._tt_lock: + self.last_timetoken = self.timetoken if self.timetoken != 0 else self.last_timetoken + self.timetoken = 0 + + if channel is None: + _invoke(error, "Channel Missing") + return + if callback is None: + _invoke(error, "Callback Missing") + return if sync is True and self.susbcribe_sync is not None: self.susbcribe_sync(args) @@ -666,18 +795,20 @@ class PubnubCoreAsync(PubnubBase): func() def _invoke_connect(): - for ch in self.subscriptions: - chobj = self.subscriptions[ch] - if chobj['connected'] is False: - chobj['connected'] = True - _invoke(chobj['connect']) + if self._channel_list_lock: + with self._channel_list_lock: + for ch in self.subscriptions: + chobj = self.subscriptions[ch] + if chobj['connected'] is False: + chobj['connected'] = True + _invoke(chobj['connect'],chobj['name']) def _invoke_error(err=None): for ch in self.subscriptions: chobj = self.subscriptions[ch] _invoke(chobj.error,err) - + ''' if callback is None: _invoke(error, "Callback Missing") return @@ -685,6 +816,7 @@ class PubnubCoreAsync(PubnubBase): if channel is None: _invoke(error, "Channel Missing") return + ''' def _get_channel(): for ch in self.subscriptions: @@ -695,22 +827,36 @@ class PubnubCoreAsync(PubnubBase): ## New Channel? if not channel in self.subscriptions: - self.subscriptions[channel] = { - 'name' : channel, - 'first' : False, - 'connected' : False, - 'subscribed' : True, - 'callback' : callback, - 'connect' : connect, - 'disconnect' : disconnect, - 'reconnect' : reconnect - } + if self._channel_list_lock: + with self._channel_list_lock: + self.subscriptions[channel] = { + 'name' : channel, + 'first' : False, + 'connected' : False, + 'subscribed' : True, + 'callback' : callback, + 'connect' : connect, + 'disconnect' : disconnect, + 'reconnect' : reconnect + } + else: + self.subscriptions[channel] = { + 'name' : channel, + 'first' : False, + 'connected' : False, + 'subscribed' : True, + 'callback' : callback, + 'connect' : connect, + 'disconnect' : disconnect, + 'reconnect' : reconnect + } ## return if already connected to channel - if self.subscriptions[channel]['connected'] : + 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 def _connect(): @@ -718,37 +864,37 @@ class PubnubCoreAsync(PubnubBase): self._reset_offline() def sub_callback(response): - print response ## ERROR ? if not response or error in response: _invoke_error() _invoke_connect() - - self.timetoken = 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]])) - else: - response_list = response[0] - chobj = _get_channel() - for r in response_list: - if chobj: - _invoke(chobj['callback'], self.decrypt(r)) - - - _connect() + with self._tt_lock: + #print 'A tt : ', self.timetoken , ' last tt : ' , self.last_timetoken + self.timetoken = self.last_timetoken if self.timetoken == 0 and self.last_timetoken != 0 else response[1] + #print 'B tt : ', self.timetoken , ' last tt : ' , self.last_timetoken + 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]])) + else: + response_list = response[0] + chobj = _get_channel() + for r in response_list: + if chobj: + _invoke(chobj['callback'], self.decrypt(r)) + + #with self._tt_lock: + # self.timetoken = self.last_timetoken if self.timetoken == 0 and self.last_timetoken != 0 else response[1] + _connect() channel_list = self.get_channel_list(self.subscriptions) - print channel_list ## CONNECT TO PUBNUB SUBSCRIBE SERVERS try: self.SUB_RECEIVER = self._request( { "urlcomponents" : [ @@ -759,6 +905,7 @@ class PubnubCoreAsync(PubnubBase): str(self.timetoken) ], "urlparams" : {"uuid":self.uuid} }, sub_callback, single=True ) except Exception as e: + print e self.timeout( 1, _connect) return @@ -837,6 +984,7 @@ class Pubnub(PubnubCoreAsync): self.headers['V'] = self.version self.http = tornado.httpclient.AsyncHTTPClient(max_clients=1000) self.id = None + self._channel_list_lock = None def _request( self, request, callback, single=False ) : url = self.getUrl(request) -- cgit v1.2.3 From 150ae1566d813acbb773839e919db2c0f467931c Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 16 Apr 2014 00:00:40 +0530 Subject: adding code to support async and pam client capabilities with python v2 and v3 --- python-tornado/Pubnub.py | 286 +++++++++++++++++++++-------------------------- 1 file changed, 129 insertions(+), 157 deletions(-) (limited to 'python-tornado/Pubnub.py') diff --git a/python-tornado/Pubnub.py b/python-tornado/Pubnub.py index 61f7c3d..ccff021 100644 --- a/python-tornado/Pubnub.py +++ b/python-tornado/Pubnub.py @@ -176,12 +176,13 @@ import time import hashlib import uuid import sys -from urllib import quote + +try: from urllib.parse import quote +except: from urllib2 import quote from base64 import urlsafe_b64encode from hashlib import sha256 -from urllib import quote -from urllib import urlopen + import hmac @@ -233,12 +234,11 @@ class PubnubBase(object): 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: self.python_version = 3 self.pc = PubnubCrypto3() - if not isinstance(self.uuid, str): raise AttributeError("pres_uuid must be a string") @@ -357,7 +357,10 @@ class PubnubBase(object): if (callback != None): callback({'message' : response['message'], 'payload' : response['payload']}) else: if (callback != None):callback(response) - if (callback != None): return _new_format_callback + if (callback != None): + return _new_format_callback + else: + return None def publish( self, args ) : @@ -392,23 +395,28 @@ class PubnubBase(object): if 'callback' in args : callback = args['callback'] else : - callback = None + callback = None + + if 'error' in args : + error = args['error'] + else : + error = None - #message = json.dumps(args['message'], separators=(',',':')) message = self.encrypt(args['message']) - signature = self.sign(channel, message) + #signature = self.sign(channel, message) ## Send Message return self._request({"urlcomponents": [ 'publish', self.publish_key, self.subscribe_key, - signature, + '0', channel, '0', message - ], 'urlparams' : {'auth' : self.auth_key}}, self._return_wrapped_callback(callback)) + ], 'urlparams' : {'auth' : self.auth_key}}, callback=self._return_wrapped_callback(callback), + error=self._return_wrapped_callback(error)) def presence( self, args ) : """ @@ -472,12 +480,10 @@ class PubnubBase(object): """ channel = str(args['channel']) - ## Capture Callback - if 'callback' in args : - callback = args['callback'] - else : - callback = 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 : raise Exception('Missing Channel') @@ -488,59 +494,16 @@ class PubnubBase(object): 'v2','presence', 'sub_key', self.subscribe_key, 'channel', channel - ]}, callback); - - - def history( self, args ) : + ], 'urlparams' : {'auth' : self.auth_key}}, callback=self._return_wrapped_callback(callback), + error=self._return_wrapped_callback(error)) + + 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 = 'limit' in args and int(args['limit']) or 10 - channel = str(args['channel']) - - ## Fail if bad input. - if not channel : - raise Exception('Missing Channel') - return False - - ## Capture Callback - if 'callback' in args : - callback = args['callback'] - else : - callback = None - - ## Get History - return self._request({ "urlcomponents" : [ - 'history', - self.subscribe_key, - channel, - '0', - str(limit) - ] }, callback); - - def detailedHistory(self, args) : - """ - #** - #* Detailed History - #* - #* Load Detailed history from a channel. - #* #* @param array args with 'channel', optional: 'start', 'end', 'reverse', 'count' #* @return mixed false on fail, array on success. #* @@ -556,34 +519,21 @@ class PubnubBase(object): ## Capture User Input channel = str(args['channel']) - params = dict() - count = 100 - - if 'count' in args: - count = int(args['count']) - - params['count'] = str(count) - - if 'reverse' in args: - params['reverse'] = str(args['reverse']).lower() + callback = args['callback'] if 'callback' in args else None + error = args['error'] if 'error' in args else None - if 'start' in args: - params['start'] = str(args['start']) + params = dict() - if 'end' in args: - params['end'] = str(args['end']) + params['count'] = str(args['count']) if 'count' in args else 100 + params['reverse'] = str(args['reverse']).lower() if 'reverse' in args else 'false' + params['start'] = str(args['start']) if 'start' in args else None + params['end'] = str(args['end']) if 'end' in args else None ## Fail if bad input. if not channel : raise Exception('Missing Channel') return False - ## Capture Callback - if 'callback' in args : - callback = args['callback'] - else : - callback = None - ## Get History return self._request({ 'urlcomponents' : [ 'v2', @@ -592,7 +542,8 @@ class PubnubBase(object): self.subscribe_key, 'channel', channel, - ],'urlparams' : params }, callback=callback); + ], 'urlparams' : {'auth' : self.auth_key}}, callback=self._return_wrapped_callback(callback), + error=self._return_wrapped_callback(error)) def time(self, args = None) : """ @@ -610,10 +561,9 @@ class PubnubBase(object): """ ## Capture Callback - if args and 'callback' in args: - callback = args['callback'] - else : - callback = None + + callback = callback if args and 'callback' in args else None + time = self._request({'urlcomponents' : [ 'time', '0' @@ -637,7 +587,8 @@ class PubnubBase(object): 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()]) + url = url + '?' + "&".join([ x + "=" + str(y) for x,y in request["urlparams"].items() if y is not None]) + #print(url) return url @@ -648,9 +599,14 @@ except ImportError: import Crypto.Hash.SHA256 as digestmod sha256 = digestmod.new import hmac -import threading -from threading import current_thread -import threading + +class EmptyLock(): + def __enter__(self): + pass + def __exit__(self,a,b,c): + pass + +empty_lock = EmptyLock() class PubnubCoreAsync(PubnubBase): @@ -666,7 +622,9 @@ class PubnubCoreAsync(PubnubBase): auth_key = None, ssl_on = False, origin = 'pubsub.pubnub.com', - uuid = None + uuid = None, + _tt_lock=empty_lock, + _channel_list_lock=empty_lock ) : """ #** @@ -696,29 +654,20 @@ class PubnubCoreAsync(PubnubBase): 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 = threading.RLock() + 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 def get_channel_list(self, channels): channel = '' first = True - if self._channel_list_lock: - with self._channel_list_lock: - for ch in channels: - if not channels[ch]['subscribed']: - continue - if not first: - channel += ',' - else: - first = False - channel += ch - else: + with self._channel_list_lock: for ch in channels: if not channels[ch]['subscribed']: continue @@ -727,9 +676,15 @@ class PubnubCoreAsync(PubnubBase): else: first = False channel += ch - return channel + + def each(l, func): + if func is None: + return + for i in l: + func(i) + def subscribe( self, args=None, sync=False ) : """ #** @@ -765,12 +720,12 @@ class PubnubCoreAsync(PubnubBase): if args is None: _invoke(error, "Arguments Missing") return - channel = args['channel'] if 'channel' in args else None - callback = args['callback'] if 'callback' in args else None - connect = args['connect'] if 'connect' in args else None - disconnect = args['disconnect'] if 'disconnect' in args else None - reconnect = args['reconnect'] if 'reconnect' in args else None - error = args['error'] if 'error' in args else None + channel = args['channel'] if 'channel' in args else None + callback = args['callback'] if 'callback' in args else None + connect = args['connect'] if 'connect' in args else None + disconnect = args['disconnect'] if 'disconnect' in args else None + reconnect = args['reconnect'] if 'reconnect' in args else None + error = args['error'] if 'error' in args else None with self._tt_lock: self.last_timetoken = self.timetoken if self.timetoken != 0 else self.last_timetoken @@ -803,10 +758,15 @@ class PubnubCoreAsync(PubnubBase): chobj['connected'] = True _invoke(chobj['connect'],chobj['name']) - def _invoke_error(err=None): - for ch in self.subscriptions: - chobj = self.subscriptions[ch] - _invoke(chobj.error,err) + 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) + else: + for ch in channel_list: + chobj = self.subscriptions[ch] + _invoke(chobj['error'],err) ''' if callback is None: @@ -827,19 +787,7 @@ class PubnubCoreAsync(PubnubBase): ## New Channel? if not channel in self.subscriptions: - if self._channel_list_lock: - with self._channel_list_lock: - self.subscriptions[channel] = { - 'name' : channel, - 'first' : False, - 'connected' : False, - 'subscribed' : True, - 'callback' : callback, - 'connect' : connect, - 'disconnect' : disconnect, - 'reconnect' : reconnect - } - else: + with self._channel_list_lock: self.subscriptions[channel] = { 'name' : channel, 'first' : False, @@ -848,9 +796,11 @@ class PubnubCoreAsync(PubnubBase): 'callback' : callback, 'connect' : connect, 'disconnect' : disconnect, - 'reconnect' : reconnect + '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") @@ -865,8 +815,11 @@ class PubnubCoreAsync(PubnubBase): def sub_callback(response): ## ERROR ? - if not response or error in response: - _invoke_error() + #print response + if not response or ('message' in response and response['message'] == 'Forbidden'): + _invoke_error(response['payload']['channels'], response['message']) + _connect() + return _invoke_connect() @@ -893,7 +846,6 @@ class PubnubCoreAsync(PubnubBase): _connect() - channel_list = self.get_channel_list(self.subscriptions) ## CONNECT TO PUBNUB SUBSCRIBE SERVERS try: @@ -903,9 +855,9 @@ class PubnubCoreAsync(PubnubBase): channel_list, '0', str(self.timetoken) - ], "urlparams" : {"uuid":self.uuid} }, sub_callback, single=True ) + ], "urlparams" : {"uuid":self.uuid, "auth" : self.auth_key} }, sub_callback, sub_callback, single=True ) except Exception as e: - print e + print(e) self.timeout( 1, _connect) return @@ -926,16 +878,20 @@ class PubnubCoreAsync(PubnubBase): def unsubscribe( self, args ): - #print(args['channel']) - channel = str(args['channel']) - if not (channel in self.subscriptions): + + if 'channel' in self.subscriptions is False: return False + channel = str(args['channel']) + + ## DISCONNECT - self.subscriptions[channel]['connected'] = 0 - self.subscriptions[channel]['subscribed'] = False - self.subscriptions[channel]['timetoken'] = 0 - self.subscriptions[channel]['first'] = False + 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.CONNECT() @@ -984,9 +940,13 @@ class Pubnub(PubnubCoreAsync): self.headers['V'] = self.version self.http = tornado.httpclient.AsyncHTTPClient(max_clients=1000) self.id = None - self._channel_list_lock = None + + def _request( self, request, callback=None, error=None, single=False ) : + + def _invoke(func, data): + if func is not None: + func(data) - def _request( self, request, callback, single=False ) : url = self.getUrl(request) request = tornado.httpclient.HTTPRequest( url, 'GET', self.headers, connect_timeout=10, request_timeout=310 ) if single is True: @@ -997,18 +957,30 @@ class Pubnub(PubnubCoreAsync): if single is True: if not id == self.id: return None - + body = response._get_body() + if body is None: return - + #print(body) def handle_exc(*args): return True if response.error is not None: with ExceptionStackContext(handle_exc): response.rethrow() - elif callback: - callback(eval(response._get_body())) + return + try: + data = json.loads(body) + except TypeError as e: + try: + data = json.loads(body.decode("utf-8")) + except: + _invoke(error, {'error' : 'json decode error'}) + + if 'error' in data and 'status' in data and 'status' != 200: + _invoke(error, data) + else: + _invoke(callback, data) self.http.fetch( request=request, -- cgit v1.2.3 From 9dc2555746adf717da0db808f4096af2167a1580 Mon Sep 17 00:00:00 2001 From: Devendra Date: Thu, 17 Apr 2014 00:28:05 +0530 Subject: adding ver 1 of dev console --- python-tornado/Pubnub.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'python-tornado/Pubnub.py') diff --git a/python-tornado/Pubnub.py b/python-tornado/Pubnub.py index ccff021..757cdd7 100644 --- a/python-tornado/Pubnub.py +++ b/python-tornado/Pubnub.py @@ -291,7 +291,7 @@ class PubnubBase(object): params=params ) - signature = self._pam_sign(sign_input) + query['signature'] = self._pam_sign(sign_input) ''' url = ("https://pubsub.pubnub.com/v1/auth/{apitype}/sub-key/".format(apitype="audit" if (apicode) else "grant") + @@ -304,7 +304,7 @@ class PubnubBase(object): 'v1', 'auth', "audit" if (apicode) else "grant" , 'sub-key', self.subscribe_key - ], 'urlparams' : {'auth' : self.auth_key, 'signature' : signature}}, + ], 'urlparams' : query}, self._return_wrapped_callback(callback)) def grant( self, channel, authkey=False, read=True, write=True, ttl=5, callback=None): -- cgit v1.2.3 From 5d6a3e1356182663b03d62f9258d38459d49017e Mon Sep 17 00:00:00 2001 From: Devendra Date: Fri, 18 Apr 2014 01:23:19 +0530 Subject: fixing wrong version detection with python 2.7 --- python-tornado/Pubnub.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) (limited to 'python-tornado/Pubnub.py') diff --git a/python-tornado/Pubnub.py b/python-tornado/Pubnub.py index 757cdd7..2c6c98f 100644 --- a/python-tornado/Pubnub.py +++ b/python-tornado/Pubnub.py @@ -237,8 +237,12 @@ class PubnubBase(object): self.python_version = 2 self.pc = PubnubCrypto2() else: - self.python_version = 3 - self.pc = PubnubCrypto3() + if sys.version_info.major == 2: + self.python_version = 2 + self.pc = PubnubCrypto2() + else: + self.python_version = 3 + self.pc = PubnubCrypto3() if not isinstance(self.uuid, str): raise AttributeError("pres_uuid must be a string") @@ -318,14 +322,14 @@ class PubnubBase(object): "ttl" : ttl }, callback=callback) - def revoke( self, channel, authkey=False, read=False, write=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" : read and 1 or 0, - "w" : write and 1 or 0, + "r" : 0, + "w" : 0, "ttl" : ttl }, callback=callback) -- cgit v1.2.3 From 4926061ebebbc060d14feac9c9d6b13880205724 Mon Sep 17 00:00:00 2001 From: Devendra Date: Tue, 22 Apr 2014 23:12:05 +0530 Subject: improvements to dev console --- python-tornado/Pubnub.py | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) (limited to 'python-tornado/Pubnub.py') diff --git a/python-tornado/Pubnub.py b/python-tornado/Pubnub.py index 2c6c98f..73cb62d 100644 --- a/python-tornado/Pubnub.py +++ b/python-tornado/Pubnub.py @@ -592,7 +592,6 @@ class PubnubBase(object): ]) 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]) - #print(url) return url @@ -682,6 +681,15 @@ class PubnubCoreAsync(PubnubBase): channel += ch return channel + def get_channel_array(self): + channels = self.subscriptions + channel = [] + with self._channel_list_lock: + for ch in channels: + if not channels[ch]['subscribed']: + continue + channel.append(ch) + return channel def each(l, func): if func is None: @@ -790,7 +798,7 @@ class PubnubCoreAsync(PubnubBase): ## New Channel? - if not channel in self.subscriptions: + if not channel in self.subscriptions or self.subscriptions[channel]['subscribed'] is False: with self._channel_list_lock: self.subscriptions[channel] = { 'name' : channel, @@ -819,7 +827,6 @@ class PubnubCoreAsync(PubnubBase): def sub_callback(response): ## ERROR ? - #print response if not response or ('message' in response and response['message'] == 'Forbidden'): _invoke_error(response['payload']['channels'], response['message']) _connect() @@ -828,9 +835,7 @@ class PubnubCoreAsync(PubnubBase): _invoke_connect() with self._tt_lock: - #print 'A tt : ', self.timetoken , ' last tt : ' , self.last_timetoken self.timetoken = self.last_timetoken if self.timetoken == 0 and self.last_timetoken != 0 else response[1] - #print 'B tt : ', self.timetoken , ' last tt : ' , self.last_timetoken if len(response) > 2: channel_list = response[2].split(',') response_list = response[0] @@ -845,12 +850,13 @@ class PubnubCoreAsync(PubnubBase): if chobj: _invoke(chobj['callback'], self.decrypt(r)) - #with self._tt_lock: - # self.timetoken = self.last_timetoken if self.timetoken == 0 and self.last_timetoken != 0 else response[1] _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" : [ @@ -867,7 +873,6 @@ class PubnubCoreAsync(PubnubBase): self._connect = _connect - ## BEGIN SUBSCRIPTION (LISTEN FOR MESSAGES) _connect() @@ -927,6 +932,7 @@ class Pubnub(PubnubCoreAsync): subscribe_key, secret_key = False, cipher_key = False, + auth_key = False, ssl_on = False, origin = 'pubsub.pubnub.com' ) : @@ -935,6 +941,7 @@ class Pubnub(PubnubCoreAsync): subscribe_key=subscribe_key, secret_key=secret_key, cipher_key=cipher_key, + auth_key=auth_key, ssl_on=ssl_on, origin=origin, ) -- cgit v1.2.3 From b2f1e0ed2337b61073a595eaf36afd718a21a3fe Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 23 Apr 2014 02:10:55 +0530 Subject: fixing issues reported by Dara in dev console --- python-tornado/Pubnub.py | 1 + 1 file changed, 1 insertion(+) (limited to 'python-tornado/Pubnub.py') diff --git a/python-tornado/Pubnub.py b/python-tornado/Pubnub.py index 73cb62d..5607df0 100644 --- a/python-tornado/Pubnub.py +++ b/python-tornado/Pubnub.py @@ -666,6 +666,7 @@ class PubnubCoreAsync(PubnubBase): 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 = '' -- cgit v1.2.3 From 09cd0c015ae276aa849297a6a976065b2b3f247b Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 23 Apr 2014 14:03:13 +0530 Subject: modifying code for pep 8 compliance --- python-tornado/Pubnub.py | 566 ++++++++++++++++++++++------------------------- 1 file changed, 261 insertions(+), 305 deletions(-) (limited to 'python-tornado/Pubnub.py') diff --git a/python-tornado/Pubnub.py b/python-tornado/Pubnub.py index 5607df0..718d74e 100644 --- a/python-tornado/Pubnub.py +++ b/python-tornado/Pubnub.py @@ -12,11 +12,12 @@ 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 @@ -27,8 +28,8 @@ class PubnubCrypto2() : pc = PubnubCrypto """ - - def pad( self, msg, block_size=16 ): + + def pad(self, msg, block_size=16): """ #** #* pad @@ -40,9 +41,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 @@ -53,7 +54,7 @@ class PubnubCrypto2() : """ return msg[0:-ord(msg[-1])] - def getSecret( self, key ): + def getSecret(self, key): """ #** #* getSecret @@ -64,7 +65,7 @@ class PubnubCrypto2() : """ return hashlib.sha256(key).hexdigest() - def encrypt( self, key, msg ): + def encrypt(self, key, msg): """ #** #* encrypt @@ -74,11 +75,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 @@ -88,12 +90,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 @@ -104,8 +106,8 @@ class PubnubCrypto3() : pc = PubnubCrypto """ - - def pad( self, msg, block_size=16 ): + + def pad(self, msg, block_size=16): """ #** #* pad @@ -117,9 +119,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 @@ -130,7 +132,7 @@ class PubnubCrypto3() : """ return msg[0:-ord(msg[-1])] - def getSecret( self, key ): + def getSecret(self, key): """ #** #* getSecret @@ -141,7 +143,7 @@ class PubnubCrypto3() : """ return hashlib.sha256(key.encode("utf-8")).hexdigest() - def encrypt( self, key, msg ): + def encrypt(self, key, msg): """ #** #* encrypt @@ -151,10 +153,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 @@ -164,40 +168,46 @@ 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') -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 @@ -209,45 +219,47 @@ 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") - def sign(self, channel, message): + ''' + + def _sign(self, channel, message): ## Sign Message if self.secret_key: signature = hashlib.md5('/'.join([ @@ -260,8 +272,9 @@ class PubnubBase(object): else: signature = '0' 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( @@ -270,7 +283,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: @@ -297,57 +310,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: @@ -358,16 +364,18 @@ 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( self, args ) : + def publish(channel, message, callback=None, error=None): """ #** #* Publish @@ -388,28 +396,9 @@ class PubnubBase(object): print(info) """ - ## Fail if bad input. - if not (args['channel'] and args['message']) : - return [ 0, 'Missing Channel or Message' ] - - ## Capture User Input - channel = str(args['channel']) - - ## Capture Callback - if 'callback' in args : - callback = args['callback'] - else : - callback = None - - if 'error' in args : - error = args['error'] - else : - error = None message = self.encrypt(args['message']) - #signature = self.sign(channel, message) - ## Send Message return self._request({"urlcomponents": [ 'publish', @@ -419,10 +408,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, args ) : + ], '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 @@ -441,29 +431,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)}) - ## Fail if missing channel - if not 'channel' in args : - raise Exception('Missing Channel.') - return False - - ## Fail if missing callback - if not 'callback' in args : - raise Exception('Missing Callback.') - return False - - ## Capture User Input - channel = str(args['channel']) - callback = args['callback'] - subscribe_key = args.get('subscribe_key') or self.subscribe_key - - return self.subscribe({'channel': channel+'-pnpres', 'subscribe_key':subscribe_key, 'callback': self._return_wrapped_callback(callback)}) - - - def here_now( self, args ) : + def here_now(self, channel, callback, error=None): """ #** #* Here Now @@ -484,33 +460,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, args) : + 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({ @@ -520,36 +494,27 @@ class PubnubBase(object): print(history) """ - ## Capture User Input - channel = str(args['channel']) - callback = args['callback'] if 'callback' in args else None - error = args['error'] if 'error' in args else None + params = dict() - params = dict() - - params['count'] = str(args['count']) if 'count' in args else 100 - params['reverse'] = str(args['reverse']).lower() if 'reverse' in args else 'false' - params['start'] = str(args['start']) if 'start' in args else None - params['end'] = str(args['end']) if 'end' in args else None - - ## Fail if bad input. - if not channel : - raise Exception('Missing Channel') - return False + 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, args = None) : + def time(self, callback=None): """ #** #* Time @@ -564,34 +529,31 @@ class PubnubBase(object): print(timestamp) """ - ## Capture Callback - callback = callback if args and 'callback' in args else None - - 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 @@ -603,32 +565,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 @@ -655,18 +623,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 = '' @@ -698,7 +666,8 @@ class PubnubCoreAsync(PubnubBase): for i in l: func(i) - def subscribe( self, args=None, sync=False ) : + def subscribe(self, channel, callback, error=None, + connect=None, disconnect=None, reconnect=None, sync=False): """ #** #* Subscribe @@ -730,32 +699,17 @@ class PubnubCoreAsync(PubnubBase): }) """ - if args is None: - _invoke(error, "Arguments Missing") - return - channel = args['channel'] if 'channel' in args else None - callback = args['callback'] if 'callback' in args else None - connect = args['connect'] if 'connect' in args else None - disconnect = args['disconnect'] if 'disconnect' in args else None - reconnect = args['reconnect'] if 'reconnect' in args else None - error = args['error'] if 'error' in args else None 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 channel is None: - _invoke(error, "Channel Missing") - return - if callback is None: - _invoke(error, "Callback Missing") - return - 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) @@ -769,27 +723,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) - - ''' - if callback is None: - _invoke(error, "Callback Missing") - return - - if channel is None: - _invoke(error, "Channel Missing") - return - ''' + _invoke(chobj['error'], err) def _get_channel(): for ch in self.subscriptions: @@ -797,53 +741,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() @@ -853,23 +802,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 @@ -886,22 +837,18 @@ class PubnubCoreAsync(PubnubBase): self._reset_offline() self._connect() + def unsubscribe(self, channel): - def unsubscribe( self, args ): - - if 'channel' in self.subscriptions is False: + if channel in self.subscriptions is False: return False - channel = str(args['channel']) - - ## 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() @@ -920,23 +867,28 @@ from tornado.stack_context import ExceptionStackContext ioloop = tornado.ioloop.IOLoop.instance() + class Pubnub(PubnubCoreAsync): - def stop(self): ioloop.stop() - def start(self): ioloop.start() - def timeout( self, delay, callback): - ioloop.add_timeout( time.time()+float(delay), callback ) - + def stop(self): + ioloop.stop() + + def start(self): + ioloop.start() + + def timeout(self, delay, callback): + ioloop.add_timeout(time.time() + float(delay), callback) + def __init__( self, publish_key, subscribe_key, - secret_key = False, - cipher_key = False, - auth_key = False, - ssl_on = False, - origin = 'pubsub.pubnub.com' - ) : + secret_key=False, + cipher_key=False, + auth_key=False, + ssl_on=False, + origin='pubsub.pubnub.com' + ): super(Pubnub, self).__init__( publish_key=publish_key, subscribe_key=subscribe_key, @@ -945,22 +897,26 @@ class Pubnub(PubnubCoreAsync): auth_key=auth_key, ssl_on=ssl_on, origin=origin, - ) + ) self.headers = {} self.headers['User-Agent'] = 'Python-Tornado' self.headers['Accept-Encoding'] = self.accept_encoding self.headers['V'] = self.version self.http = tornado.httpclient.AsyncHTTPClient(max_clients=1000) self.id = None - - def _request( self, request, callback=None, error=None, single=False ) : + + def _request(self, request, callback=None, error=None, single=False): def _invoke(func, data): if func is not None: func(data) url = self.getUrl(request) - request = tornado.httpclient.HTTPRequest( url, 'GET', self.headers, connect_timeout=10, request_timeout=310 ) + request = tornado.httpclient.HTTPRequest( + url, 'GET', + self.headers, + connect_timeout=10, + request_timeout=310) if single is True: id = time.time() self.id = id @@ -968,13 +924,14 @@ class Pubnub(PubnubCoreAsync): def responseCallback(response): if single is True: if not id == self.id: - return None - + return None + body = response._get_body() if body is None: return #print(body) + def handle_exc(*args): return True if response.error is not None: @@ -987,7 +944,7 @@ class Pubnub(PubnubCoreAsync): try: data = json.loads(body.decode("utf-8")) except: - _invoke(error, {'error' : 'json decode error'}) + _invoke(error, {'error': 'json decode error'}) if 'error' in data and 'status' in data and 'status' != 200: _invoke(error, data) @@ -1003,4 +960,3 @@ class Pubnub(PubnubCoreAsync): pass return abort - -- cgit v1.2.3 From f7b89bfafae34fa22509c1d1c59d1284ec62c5df Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 23 Apr 2014 21:35:06 +0530 Subject: exception handling changes --- python-tornado/Pubnub.py | 53 +++++++++++++++++++++++------------------------- 1 file changed, 25 insertions(+), 28 deletions(-) (limited to 'python-tornado/Pubnub.py') diff --git a/python-tornado/Pubnub.py b/python-tornado/Pubnub.py index 718d74e..3d0ba1d 100644 --- a/python-tornado/Pubnub.py +++ b/python-tornado/Pubnub.py @@ -186,7 +186,7 @@ import sys try: from urllib.parse import quote -except: +except ImportError: from urllib2 import quote from base64 import urlsafe_b64encode @@ -397,7 +397,7 @@ class PubnubBase(object): """ - message = self.encrypt(args['message']) + message = self.encrypt(message) ## Send Message return self._request({"urlcomponents": [ @@ -458,15 +458,6 @@ class PubnubBase(object): print(here_now['uuids']) """ - channel = str(args['channel']) - - 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: - raise Exception('Missing Channel') - return False ## Get Presence Here Now return self._request({"urlcomponents": [ @@ -807,21 +798,23 @@ class PubnubCoreAsync(PubnubBase): return ## CONNECT TO PUBNUB SUBSCRIBE SERVERS - try: - 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) + #try: + 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) + ''' except Exception as e: print(e) self.timeout(1, _connect) return + ''' self._connect = _connect @@ -905,7 +898,8 @@ class Pubnub(PubnubCoreAsync): self.http = tornado.httpclient.AsyncHTTPClient(max_clients=1000) self.id = None - def _request(self, request, callback=None, error=None, single=False): + def _request(self, request, callback=None, error=None, + single=False, read_timeout=5, connect_timeout=5): def _invoke(func, data): if func is not None: @@ -915,8 +909,8 @@ class Pubnub(PubnubCoreAsync): request = tornado.httpclient.HTTPRequest( url, 'GET', self.headers, - connect_timeout=10, - request_timeout=310) + connect_timeout=connect_timeout, + request_timeout=read_timeout) if single is True: id = time.time() self.id = id @@ -930,20 +924,23 @@ class Pubnub(PubnubCoreAsync): if body is None: return - #print(body) def handle_exc(*args): return True if response.error is not None: with ExceptionStackContext(handle_exc): - response.rethrow() + if response.code in [403, 401]: + response.rethrow() + else: + _invoke(error, {"message": response.reason}) return + try: data = json.loads(body) except TypeError as e: try: data = json.loads(body.decode("utf-8")) - except: + except ValueError as ve: _invoke(error, {'error': 'json decode error'}) if 'error' in data and 'status' in data and 'status' != 200: -- cgit v1.2.3 From c5d2fb446378e78e9e164dbea969edd57314dc4b Mon Sep 17 00:00:00 2001 From: Devendra Date: Thu, 24 Apr 2014 00:59:50 +0530 Subject: removing files --- python-tornado/Pubnub.py | 959 ----------------------------------------------- 1 file changed, 959 deletions(-) delete mode 100644 python-tornado/Pubnub.py (limited to 'python-tornado/Pubnub.py') diff --git a/python-tornado/Pubnub.py b/python-tornado/Pubnub.py deleted file mode 100644 index 3d0ba1d..0000000 --- a/python-tornado/Pubnub.py +++ /dev/null @@ -1,959 +0,0 @@ -## www.pubnub.com - PubNub Real-time push service in the cloud. -# coding=utf8 - -## PubNub Real-time Push APIs and Notifications Framework -## Copyright (c) 2010 Stephen Blum -## http://www.pubnub.com/ - -## ----------------------------------- -## PubNub 3.3.5 Real-time Push Cloud API -## ----------------------------------- - - -from Crypto.Cipher import AES -from Crypto.Hash import MD5 -from base64 import encodestring, decodestring -import hashlib -import hmac - - -class PubnubCrypto2(): - """ - #** - #* PubnubCrypto - #* - #** - - ## Initiate Class - pc = PubnubCrypto - - """ - - def pad(self, msg, block_size=16): - """ - #** - #* pad - #* - #* pad the text to be encrypted - #* appends a padding character to the end of the String - #* until the string has block_size length - #* @return msg with padding. - #** - """ - padding = block_size - (len(msg) % block_size) - return msg + chr(padding) * padding - - def depad(self, msg): - """ - #** - #* depad - #* - #* depad the decryptet message" - #* @return msg without padding. - #** - """ - return msg[0:-ord(msg[-1])] - - def getSecret(self, key): - """ - #** - #* getSecret - #* - #* hases the key to MD5 - #* @return key in MD5 format - #** - """ - return hashlib.sha256(key).hexdigest() - - def encrypt(self, key, msg): - """ - #** - #* encrypt - #* - #* encrypts the message - #* @return message in encrypted format - #** - """ - secret = self.getSecret(key) - 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): - """ - #** - #* decrypt - #* - #* decrypts the message - #* @return message in decryped format - #** - """ - secret = self.getSecret(key) - Initial16bytes = '0123456789012345' - cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes) - return self.depad((cipher.decrypt(decodestring(msg)))) - - -class PubnubCrypto3(): - """ - #** - #* PubnubCrypto - #* - #** - - ## Initiate Class - pc = PubnubCrypto - - """ - - def pad(self, msg, block_size=16): - """ - #** - #* pad - #* - #* pad the text to be encrypted - #* appends a padding character to the end of the String - #* until the string has block_size length - #* @return msg with padding. - #** - """ - padding = block_size - (len(msg) % block_size) - return msg + (chr(padding) * padding).encode('utf-8') - - def depad(self, msg): - """ - #** - #* depad - #* - #* depad the decryptet message" - #* @return msg without padding. - #** - """ - return msg[0:-ord(msg[-1])] - - def getSecret(self, key): - """ - #** - #* getSecret - #* - #* hases the key to MD5 - #* @return key in MD5 format - #** - """ - return hashlib.sha256(key.encode("utf-8")).hexdigest() - - def encrypt(self, key, msg): - """ - #** - #* encrypt - #* - #* encrypts the message - #* @return message in encrypted format - #** - """ - 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): - """ - #** - #* decrypt - #* - #* decrypts the message - #* @return message in decryped format - #** - """ - 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') - - -try: - import json -except ImportError: - import simplejson as json - -import time -import hashlib -import uuid -import sys - -try: - from urllib.parse import quote -except ImportError: - from urllib2 import quote - -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 - ): - """ - #** - #* Pubnub - #* - #* Init the Pubnub Client API - #* - #* @param string publish_key required key to send messages. - #* @param string subscribe_key required key to receive messages. - #* @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) - #** - - ## Initiat Class - pubnub = Pubnub( 'PUBLISH-KEY', 'SUBSCRIBE-KEY', 'SECRET-KEY', False ) - - """ - 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 - - if self.ssl: - self.origin = 'https://' + 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() - else: - if sys.version_info.major == 2: - self.python_version = 2 - self.pc = PubnubCrypto2() - else: - self.python_version = 3 - self.pc = PubnubCrypto3() - - if not isinstance(self.uuid, str): - raise AttributeError("pres_uuid must be a string") - - ''' - - def _sign(self, channel, message): - ## Sign Message - if self.secret_key: - signature = hashlib.md5('/'.join([ - self.publish_key, - self.subscribe_key, - self.secret_key, - channel, - message - ])).hexdigest() - else: - signature = '0' - return signature - ''' - - def _pam_sign(self, msg): - """Calculate a signature by secret key and message.""" - - return urlsafe_b64encode(hmac.new( - self.secret_key.encode("utf-8"), - msg.encode("utf-8"), - sha256 - ).digest()) - - def _pam_auth(self, query, apicode=0, callback=None): - """Issue an authenticated request.""" - - if 'timestamp' not in query: - query['timestamp'] = int(time.time()) - - ## Global Grant? - if 'auth' in query and not query['auth']: - del query['auth'] - - if 'channel' in query and not query['channel']: - del query['channel'] - - params = "&".join([ - x + "=" + quote( - str(query[x]), safe="" - ) for x in sorted(query) - ]) - sign_input = "{subkey}\n{pubkey}\n{apitype}\n{params}".format( - subkey=self.subscribe_key, - pubkey=self.publish_key, - apitype="audit" if (apicode) else "grant", - params=params - ) - - query['signature'] = self._pam_sign(sign_input) - - return self._request({"urlcomponents": [ - 'v1', 'auth', "audit" if (apicode) else "grant", - 'sub-key', - self.subscribe_key - ], 'urlparams': query}, - self._return_wrapped_callback(callback)) - - 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 - }, callback=callback) - - 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 - }, callback=callback) - - def audit(self, channel=False, authkey=False, callback=None): - return self._pam_auth({ - "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(message) - - return message - - def decrypt(self, message): - if self.cipher_key: - message = self.pc.decrypt(self.cipher_key, message) - - return message - - def _return_wrapped_callback(self, callback=None): - def _new_format_callback(response): - if 'payload' in response: - if (callback is not None): - callback({'message': response['message'], - 'payload': response['payload']}) - else: - 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): - """ - #** - #* Publish - #* - #* Send a message to a channel. - #* - #* @param array args with channel and message. - #* @return array success information. - #** - - ## Publish Example - info = pubnub.publish({ - 'channel' : 'hello_world', - 'message' : { - 'some_text' : 'Hello my World' - } - }) - print(info) - - """ - - message = self.encrypt(message) - - ## Send Message - return self._request({"urlcomponents": [ - 'publish', - self.publish_key, - self.subscribe_key, - '0', - 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): - """ - #** - #* presence - #* - #* This is BLOCKING. - #* Listen for presence events on a channel. - #* - #* @param array args with channel and callback. - #* @return false on fail, array on success. - #** - - ## Presence Example - def pres_event(message) : - print(message) - return True - - pubnub.presence({ - 'channel' : 'hello_world', - '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): - """ - #** - #* Here Now - #* - #* Load current occupancy from a channel. - #* - #* @param array args with 'channel'. - #* @return mixed false on fail, array on success. - #* - - ## Presence Example - here_now = pubnub.here_now({ - 'channel' : 'hello_world', - }) - print(here_now['occupancy']) - print(here_now['uuids']) - - """ - - ## Get Presence Here Now - return self._request({"urlcomponents": [ - '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)) - - def history(self, channel, count=100, reverse=False, - start=None, end=None, callback=None, error=None): - """ - #** - #* History - #* - #* Load history from a channel. - #* - - ## History Example - history = pubnub.detailedHistory({ - 'channel' : 'hello_world', - 'count' : 5 - }) - print(history) - - """ - - params = dict() - - params['count'] = count - params['reverse'] = reverse - params['start'] = start - params['end'] = end - - ## Get History - 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)) - - def time(self, callback=None): - """ - #** - #* Time - #* - #* Timestamp from PubNub Cloud. - #* - #* @return int timestamp. - #* - - ## PubNub Server Time Example - timestamp = pubnub.time() - print(timestamp) - - """ - - time = self._request({'urlcomponents': [ - 'time', - '0' - ]}, callback) - if time is not None: - return time[0] - - 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): - ## 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 ("urlparams" in request): - url = url + '?' + "&".join([x + "=" + str(y) for x, y in request[ - "urlparams"].items() if y is not None]) - return url - - -try: - from hashlib import sha256 - digestmod = sha256 -except ImportError: - import Crypto.Hash.SHA256 as digestmod - sha256 = digestmod.new -import hmac - - -class EmptyLock(): - def __enter__(self): - pass - - def __exit__(self, a, b, c): - pass - -empty_lock = EmptyLock() - - -class PubnubCoreAsync(PubnubBase): - - 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, - _tt_lock=empty_lock, - _channel_list_lock=empty_lock - ): - """ - #** - #* Pubnub - #* - #* Init the Pubnub Client API - #* - #* @param string publish_key required key to send messages. - #* @param string subscribe_key required key to receive messages. - #* @param string secret_key required key to sign messages. - #* @param boolean ssl required for 2048 bit encrypted messages. - #* @param string origin PUBNUB Server Origin. - #** - - ## Initiat Class - pubnub = Pubnub( 'PUBLISH-KEY', 'SUBSCRIBE-KEY', 'SECRET-KEY', False ) - - """ - super(PubnubCoreAsync, self).__init__( - publish_key=publish_key, - subscribe_key=subscribe_key, - secret_key=secret_key, - cipher_key=cipher_key, - auth_key=auth_key, - 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 - - def get_channel_list(self, channels): - channel = '' - first = True - with self._channel_list_lock: - for ch in channels: - if not channels[ch]['subscribed']: - continue - if not first: - channel += ',' - else: - first = False - channel += ch - return channel - - def get_channel_array(self): - channels = self.subscriptions - channel = [] - with self._channel_list_lock: - for ch in channels: - if not channels[ch]['subscribed']: - continue - channel.append(ch) - return channel - - def each(l, func): - if func is None: - return - for i in l: - func(i) - - def subscribe(self, channel, callback, error=None, - connect=None, disconnect=None, reconnect=None, sync=False): - """ - #** - #* Subscribe - #* - #* This is NON-BLOCKING. - #* Listen for a message on a channel. - #* - #* @param array args with channel and message. - #* @return false on fail, array on success. - #** - - ## Subscribe Example - def receive(message) : - print(message) - return True - - ## On Connect Callback - def connected() : - pubnub.publish({ - 'channel' : 'hello_world', - 'message' : { 'some_var' : 'text' } - }) - - ## Subscribe - pubnub.subscribe({ - 'channel' : 'hello_world', - 'connect' : connected, - 'callback' : receive - }) - - """ - - with self._tt_lock: - 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): - if func is not None: - if msg is not None: - func(msg) - else: - func() - - def _invoke_connect(): - if self._channel_list_lock: - with self._channel_list_lock: - for ch in self.subscriptions: - chobj = self.subscriptions[ch] - if chobj['connected'] is False: - chobj['connected'] = True - _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) - else: - for ch in channel_list: - chobj = self.subscriptions[ch] - _invoke(chobj['error'], err) - - def _get_channel(): - for ch in self.subscriptions: - chobj = self.subscriptions[ch] - 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 - } - - ## 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 - - ## 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 - - _invoke_connect() - - with self._tt_lock: - 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]])) - else: - response_list = response[0] - chobj = _get_channel() - for r in response_list: - if chobj: - _invoke(chobj['callback'], self.decrypt(r)) - - _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": [ - 'subscribe', - self.subscribe_key, - channel_list, - '0', - str(self.timetoken) - ], "urlparams": {"uuid": self.uuid, "auth": self.auth_key}}, - sub_callback, - sub_callback, - single=True) - ''' - except Exception as e: - print(e) - self.timeout(1, _connect) - return - ''' - - self._connect = _connect - - ## BEGIN SUBSCRIPTION (LISTEN FOR MESSAGES) - _connect() - - def _reset_offline(self): - if self.SUB_RECEIVER is not None: - self.SUB_RECEIVER() - self.SUB_RECEIVER = None - - def CONNECT(self): - self._reset_offline() - self._connect() - - def unsubscribe(self, channel): - - if channel in self.subscriptions is False: - return False - - ## 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.CONNECT() - - -import tornado.httpclient - -try: - from hashlib import sha256 - digestmod = sha256 -except ImportError: - import Crypto.Hash.SHA256 as digestmod - sha256 = digestmod.new - -import hmac -import tornado.ioloop -from tornado.stack_context import ExceptionStackContext - -ioloop = tornado.ioloop.IOLoop.instance() - - -class Pubnub(PubnubCoreAsync): - - def stop(self): - ioloop.stop() - - def start(self): - ioloop.start() - - def timeout(self, delay, callback): - ioloop.add_timeout(time.time() + float(delay), callback) - - def __init__( - self, - publish_key, - subscribe_key, - secret_key=False, - cipher_key=False, - auth_key=False, - ssl_on=False, - origin='pubsub.pubnub.com' - ): - super(Pubnub, self).__init__( - publish_key=publish_key, - subscribe_key=subscribe_key, - secret_key=secret_key, - cipher_key=cipher_key, - auth_key=auth_key, - ssl_on=ssl_on, - origin=origin, - ) - self.headers = {} - self.headers['User-Agent'] = 'Python-Tornado' - self.headers['Accept-Encoding'] = self.accept_encoding - self.headers['V'] = self.version - self.http = tornado.httpclient.AsyncHTTPClient(max_clients=1000) - self.id = None - - def _request(self, request, callback=None, error=None, - single=False, read_timeout=5, connect_timeout=5): - - def _invoke(func, data): - if func is not None: - func(data) - - url = self.getUrl(request) - request = tornado.httpclient.HTTPRequest( - url, 'GET', - self.headers, - connect_timeout=connect_timeout, - request_timeout=read_timeout) - if single is True: - id = time.time() - self.id = id - - def responseCallback(response): - if single is True: - if not id == self.id: - return None - - body = response._get_body() - - if body is None: - return - - def handle_exc(*args): - return True - if response.error is not None: - with ExceptionStackContext(handle_exc): - if response.code in [403, 401]: - response.rethrow() - else: - _invoke(error, {"message": response.reason}) - return - - try: - data = json.loads(body) - except TypeError as e: - try: - data = json.loads(body.decode("utf-8")) - except ValueError as ve: - _invoke(error, {'error': 'json decode error'}) - - if 'error' in data and 'status' in data and 'status' != 200: - _invoke(error, data) - else: - _invoke(callback, data) - - self.http.fetch( - request=request, - callback=responseCallback - ) - - def abort(): - pass - - return abort -- cgit v1.2.3