diff options
Diffstat (limited to 'python-tornado')
| -rw-r--r-- | python-tornado/Pubnub.py | 450 | ||||
| -rw-r--r-- | python-tornado/Pubnub.pyc | bin | 0 -> 10623 bytes | |||
| -rw-r--r-- | python-tornado/PubnubCrypto.py | 92 | ||||
| -rw-r--r-- | python-tornado/PubnubCrypto.pyc | bin | 0 -> 2619 bytes | |||
| -rw-r--r-- | python-tornado/README | 108 | ||||
| -rw-r--r-- | python-tornado/examples/history-example.py | 44 | ||||
| -rw-r--r-- | python-tornado/examples/publish-example.py | 44 | ||||
| -rw-r--r-- | python-tornado/examples/subscribe-example.py | 60 | ||||
| -rw-r--r-- | python-tornado/examples/uuid-example.py | 28 | ||||
| -rw-r--r-- | python-tornado/tests/benchmark.py | 96 | ||||
| -rw-r--r-- | python-tornado/tests/delivery.py | 161 | ||||
| -rw-r--r-- | python-tornado/tests/unit-test.py | 224 | 
12 files changed, 1307 insertions, 0 deletions
| diff --git a/python-tornado/Pubnub.py b/python-tornado/Pubnub.py new file mode 100644 index 0000000..12baf17 --- /dev/null +++ b/python-tornado/Pubnub.py @@ -0,0 +1,450 @@ +## 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.1 Real-time Push Cloud API +## ----------------------------------- + +import json +import time +import hashlib +import urllib2 +import tornado.httpclient +import sys +import uuid + +try: +    from hashlib import sha256 +    digestmod = sha256 +except ImportError: +    import Crypto.Hash.SHA256 as digestmod +    sha256 = digestmod.new + +import hmac +import tornado.ioloop +from PubnubCrypto import PubnubCrypto + +ioloop = tornado.ioloop.IOLoop.instance() + +class Pubnub(): + +    def stop(self): ioloop.stop() +    def start(self): ioloop.start() +    def timeout( self, callback, delay ): +        ioloop.add_timeout( time.time()+float(delay), callback ) +         +    def __init__( +        self, +        publish_key, +        subscribe_key, +        secret_key = False, +        cipher_key = False, +        ssl_on = False, +        origin = 'pubsub.pubnub.com' +    ) : +        """ +        #** +        #* 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 ) + +        """ +        self.origin        = origin +        self.publish_key   = publish_key +        self.subscribe_key = subscribe_key +        self.secret_key    = secret_key +        self.cipher_key    = cipher_key +        self.ssl           = ssl_on +        self.subscriptions = {} + +        if self.ssl : +            self.origin = 'https://' + self.origin +        else : +            self.origin = 'http://'  + self.origin + + +    def publish( self, args ) : +        """ +        #** +        #* Publish +        #* +        #* Send a message to a channel. +        #* +        #* @param array args with channel and message. +        #* @return array success information. +        #** + +        ## Publish Example +        def publish_complete(info): +            print(info) + +        pubnub.publish({ +            'channel' : 'hello_world', +            'message' : { +                'some_text' : 'Hello my World' +            }, +            'callback' : publish_complete +        }) + +        """ +        ## Fail if bad input. +        if not (args['channel'] and args['message']) : +            print('Missing Channel or Message') +            return False + +        ## Capture User Input +        channel = str(args['channel']) +        message = args['message'] + +        if self.cipher_key : +            pc = PubnubCrypto() +            out = [] +            if type( message ) == type(list()): +                for item in message: +                    encryptItem = pc.encrypt(self.cipher_key, item ).rstrip() +                    out.append(encryptItem) +                message = json.dumps(out) +            elif type( message ) == type(dict()): +                outdict = {} +                for k, item in message.iteritems(): +                    encryptItem = pc.encrypt(self.cipher_key, item ).rstrip() +                    outdict[k] = encryptItem +                    out.append(outdict) +                message = json.dumps(out[0]) +            else: +                message = json.dumps(pc.encrypt(self.cipher_key, message).replace('\n','')) +        else : +            message = json.dumps(args['message']) + +        ## Capture Callback +        if args.has_key('callback') : +            callback = args['callback'] +        else : +            callback = lambda x : x + +        ## Sign Message +        if self.secret_key : +            hashObject = sha256() +            hashObject.update(self.secret_key) +            hashedSecret = hashObject.hexdigest() +            hash = hmac.HMAC(hashedSecret, '/'.join([ +                    self.publish_key, +                    self.subscribe_key, +                    self.secret_key, +                    channel, +                    message +                ]), digestmod=digestmod) +            signature = hash.hexdigest()         +        else : +            signature = '0' +         +        ## Send Message +        return self._request([ +            'publish', +            self.publish_key, +            self.subscribe_key, +            signature, +            channel, +            '0', +            message +        ], callback ); + + +    def subscribe( self, args ) : +        """ +        #** +        #* 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 +        }) + +        """ +        ## Fail if missing channel +        if not 'channel' in args : +            print('Missing Channel.') +            return False + +        ## Fail if missing callback +        if not 'callback' in args : +            print('Missing Callback.') +            return False + +        ## Capture User Input +        channel   = str(args['channel']) +        callback  = args['callback'] +        connectcb = args['connect'] + +        if 'errorback' in args: +            errorback = args['errorback'] +        else: +            errorback = lambda x: x + +        ## New Channel? +        if not (channel in self.subscriptions) : +            self.subscriptions[channel] = { +                'first'     : False, +                'connected' : 0, +                'timetoken' : '0' +            } + +        ## Ensure Single Connection +        if self.subscriptions[channel]['connected'] : +            print("Already Connected") +            return False + +        self.subscriptions[channel]['connected'] = 1 + +        ## SUBSCRIPTION RECURSION  +        def substabizel(): +            ## STOP CONNECTION? +            if not self.subscriptions[channel]['connected']: +                return + +            def sub_callback(response): +                ## STOP CONNECTION? +                if not self.subscriptions[channel]['connected']: +                    return + +                ## CONNECTED CALLBACK +                if not self.subscriptions[channel]['first'] : +                    self.subscriptions[channel]['first'] = True +                    connectcb() + +                ## PROBLEM? +                if not response: +                    def time_callback(_time): +                        if not _time: +                            ioloop.add_timeout(time.time()+1, substabizel) +                            return errorback("Lost Network Connection") +                        else: +                            ioloop.add_timeout(time.time()+1, substabizel) + +                    ## ENSURE CONNECTED (Call Time Function) +                    return self.time({ 'callback' : time_callback }) + +                self.subscriptions[channel]['timetoken'] = response[1] +                substabizel() + +                pc = PubnubCrypto() +                out = [] +                for message in response[0]: +                     if self.cipher_key : +                          if type( message ) == type(list()): +                              for item in message: +                                  encryptItem = pc.decrypt(self.cipher_key, item ) +                                  out.append(encryptItem) +                              message = out +                          elif type( message ) == type(dict()): +                              outdict = {} +                              for k, item in message.iteritems(): +                                  encryptItem = pc.decrypt(self.cipher_key, item ) +                                  outdict[k] = encryptItem +                                  out.append(outdict) +                              message = out[0] +                          else: +                              message = pc.decrypt(self.cipher_key, message ) +                           +                     callback(message) + +            ## CONNECT TO PUBNUB SUBSCRIBE SERVERS +            try : +                self._request( [ +                    'subscribe', +                    self.subscribe_key, +                    channel, +                    '0', +                    str(self.subscriptions[channel]['timetoken']) +                ], sub_callback ) +            except : +                ioloop.add_timeout(time.time()+1, substabizel) +                return + +        ## BEGIN SUBSCRIPTION (LISTEN FOR MESSAGES) +        substabizel() + + +    def unsubscribe( self, args ): +        channel = str(args['channel']) +        if not (channel in self.subscriptions): +            return False + +        ## DISCONNECT +        self.subscriptions[channel]['connected'] = 0 +        self.subscriptions[channel]['timetoken'] = 0 +        self.subscriptions[channel]['first']     = False + + +    def history( self, args ) : +        """ +        #** +        #* History +        #* +        #* Load history from a channel. +        #* +        #* @param array args with 'channel' and 'limit'. +        #* @return mixed false on fail, array on success. +        #* + +        ## History Example +        history = pubnub.history({ +            'channel' : 'hello_world', +            'limit'   : 1 +        }) +        print(history) + +        """ +        ## Capture User Input +        limit   = args.has_key('limit') and int(args['limit']) or 10 +        channel = str(args['channel']) + +        ## Fail if bad input. +        if not channel : +            print('Missing Channel') +            return False + +        ## Get History +        return self._request( [ +            'history', +            self.subscribe_key, +            channel, +            '0', +            str(limit) +        ], args['callback'] ); + +    def time( self, args ) : +        """ +        #** +        #* Time +        #* +        #* Timestamp from PubNub Cloud. +        #* +        #* @return int timestamp. +        #* + +        ## PubNub Server Time Example +        def time_complete(timestamp): +            print(timestamp) + +        pubnub.time(time_complete) + +        """ +        def complete(response) : +            args['callback'](response and response[0]) + +        self._request( [ +            'time', +            '0' +        ], complete ) +         +    def uuid(self) : +        """ +        #** +        #* uuid +        #* +        #* Generate a UUID +        #* +        #* @return  UUID. +        #* + +        ## PubNub UUID Example +        uuid = pubnub.uuid() +        print(uuid) +        """ +        return uuid.uuid1() + +    def _request( self, request, callback ) : +        ## 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]) + +        requestType = request[0] + +        def complete(response) : +            if response.error: +                return callback(None) +            obj = json.loads(response.buffer.getvalue()) +            pc = PubnubCrypto() +            out = [] +            if self.cipher_key : +                if requestType == "history" : +                    if type(obj) == type(list()): +                        for item in obj: +                            if type(item) == type(list()): +                                for subitem in item: +                                    encryptItem = pc.decrypt(self.cipher_key, subitem ) +                                    out.append(encryptItem) +                            elif type(item) == type(dict()): +                                outdict = {} +                                for k, subitem in item.iteritems(): +                                    encryptItem = pc.decrypt(self.cipher_key, subitem ) +                                    outdict[k] = encryptItem +                                    out.append(outdict) +                            else :          +                                encryptItem = pc.decrypt(self.cipher_key, item ) +                                out.append(encryptItem) +                        callback(out) +                    elif type( obj ) == type(dict()): +                        for k, item in obj.iteritems(): +                            encryptItem = pc.decrypt(self.cipher_key, item ) +                            out.append(encryptItem) +                        callback(out)     +                else : +                    callback(obj) +            else :         +                callback(obj)         + +        ## Send Request Expecting JSON Response +        http = tornado.httpclient.AsyncHTTPClient(max_clients=1000) +        request = tornado.httpclient.HTTPRequest( url, 'GET', dict({ +            'V' : '3.1', +            'User-Agent' : 'Python-Tornado', +            'Accept-Encoding' : 'gzip' +        }) )  +         +        http.fetch( +            request, +            callback=complete, +            connect_timeout=310, +            request_timeout=310 +        ) + diff --git a/python-tornado/Pubnub.pyc b/python-tornado/Pubnub.pycBinary files differ new file mode 100644 index 0000000..9ca3936 --- /dev/null +++ b/python-tornado/Pubnub.pyc diff --git a/python-tornado/PubnubCrypto.py b/python-tornado/PubnubCrypto.py new file mode 100644 index 0000000..744f2d3 --- /dev/null +++ b/python-tornado/PubnubCrypto.py @@ -0,0 +1,92 @@ +## 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.1 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 PubnubCrypto() : +    """ +    #** +    #* 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. +        #** +        """ +        return msg + ((block_size - len(msg) % block_size) * chr(block_size - len(msg) % block_size)) +        +    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 MD5.new(key).digest() + +    def encrypt( self, key, msg ): +        """ +        #** +        #* encrypt +        #* +        #* encrypts the message +        #* @return message in encrypted format +        #** +        """ +        secret = self.getSecret(key) +        Initial16bytes='0123456789012345' +        cipher = AES.new(secret,AES.MODE_CBC,Initial16bytes) +        return encodestring(cipher.encrypt(self.pad(msg))) +     +    def decrypt( self, key, msg ): +        """ +        #** +        #* decrypt +        #* +        #* decrypts the message +        #* @return message in decryped format +        #** +        """ +        secret = self.getSecret(key) +        Initial16bytes='0123456789012345' +        cipher = AES.new(secret,AES.MODE_CBC,Initial16bytes) +        return self.depad((cipher.decrypt(decodestring(msg)))) +     diff --git a/python-tornado/PubnubCrypto.pyc b/python-tornado/PubnubCrypto.pycBinary files differ new file mode 100644 index 0000000..a349424 --- /dev/null +++ b/python-tornado/PubnubCrypto.pyc diff --git a/python-tornado/README b/python-tornado/README new file mode 100644 index 0000000..d6eeebe --- /dev/null +++ b/python-tornado/README @@ -0,0 +1,108 @@ +## --------------------------------------------------- +## +## YOU MUST HAVE A PUBNUB ACCOUNT TO USE THE API. +## http://www.pubnub.com/account +## +## ---------------------------------------------------- + +## ---------------------------------------------------- +## PubNub 3.1 Real-time Cloud Push API - PYTHON TORNADO +## ---------------------------------------------------- +## +## www.pubnub.com - PubNub Real-time Push Service in the Cloud.  +## http://github.com/pubnub/pubnub-api/tree/master/python-tornado/ +## +## PubNub is a Massively Scalable Real-time Service for Web and Mobile Games. +## This is a cloud-based service for broadcasting Real-time messages +## to thousands of web and mobile clients simultaneously. + +## ---------------------------------------------------- +## Third Party Libraries Dependency +## ---------------------------------------------------- +## You must download and install, +## +## 1. pyopenssl +## Download from https://launchpad.net/pyopenssl +## +## 2. pycrypto +## Download from https://github.com/dlitz/pycrypto OR +## from http://code.google.com/p/uploadprj/downloads/detail?name=pycrypto-2.3.win32-py2.7.zip&can=2&q + +## --------------- +## Python Push API +## --------------- +pubnub = Pubnub( +    "demo",  ## PUBLISH_KEY +    "demo",  ## SUBSCRIBE_KEY +    "demo",  ## SECRET_KEY +    "",  ## CIPHER_KEY (Cipher key is Optional) +     False   ## SSL_ON? +) + +## ----------------------------------------------------------------------- +## IO Event Loop +## ----------------------------------------------------------------------- +## VERY IMPORTANT TO ADD THIS LINE AT THE VERY BOTTOM! +## +## tornado.ioloop.IOLoop.instance().start() ## IMPORTANT! +## + +## ----------------------------------------------------------------------- +## Subscribe Example +## ----------------------------------------------------------------------- + +def connected() : +    ## ----------------------------------------------------------------------- +    ## Publish Example +    ## ----------------------------------------------------------------------- +    def publish_complete(info): +        print(info) + +    pubnub.publish({ +        'channel' : "my-tornado-channel", +        'message' : { +            'some_text' : 'Hello World!' +        }, +        'callback' : publish_complete +    }) + +def message_received(message): +    print(message) + +pubnub.subscribe({ +    'channel'  : "my-tornado-channel", +    'connect'  : connected, +    'callback' : message_received +}) + +## ----------------------------------------------------------------------- +## Time Example +## ----------------------------------------------------------------------- +def time_complete(timestamp): +    print(timestamp) + +pubnub.time({ 'callback' : time_complete }) + +## ----------------------------------------------------------------------- +## History Example +## ----------------------------------------------------------------------- +def history_complete(messages): +    print(messages) + +pubnub.history( { +    'channel'  : "my-tornado-channel", +    'limit'    : 10, +    'callback' : history_complete +}) + +## ----------------------------------------------------------------------- +## UUID Example +## ----------------------------------------------------------------------- +uuid = pubnub.uuid() +print "UUID" +print uuid + +## ----------------------------------------------------------------------- +## IO Event Loop +## ----------------------------------------------------------------------- +tornado.ioloop.IOLoop.instance().start() diff --git a/python-tornado/examples/history-example.py b/python-tornado/examples/history-example.py new file mode 100644 index 0000000..5c6fb5b --- /dev/null +++ b/python-tornado/examples/history-example.py @@ -0,0 +1,44 @@ +## 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.0 Real-time Push Cloud API +## ----------------------------------- + +import sys +import tornado +sys.path.append('../') +from Pubnub import Pubnub + +publish_key   = len(sys.argv) > 1 and sys.argv[1] or 'demo' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' +secret_key    = len(sys.argv) > 3 and sys.argv[3] or 'demo' +cipher_key    = len(sys.argv) > 4 and sys.argv[4] or '' +ssl_on        = len(sys.argv) > 5 and bool(sys.argv[5]) or False + +## ----------------------------------------------------------------------- +## Initiate Pubnub State +## ----------------------------------------------------------------------- +pubnub = Pubnub( publish_key, subscribe_key, secret_key,cipher_key, ssl_on ) +crazy  = 'hello_world' + +## ----------------------------------------------------------------------- +## History Example +## ----------------------------------------------------------------------- +def history_complete(messages): +    print(messages) + +pubnub.history( { +   'channel'  : crazy, +   'limit'    : 10, +   'callback' : history_complete +}) + +## ----------------------------------------------------------------------- +## IO Event Loop +## ----------------------------------------------------------------------- +tornado.ioloop.IOLoop.instance().start() diff --git a/python-tornado/examples/publish-example.py b/python-tornado/examples/publish-example.py new file mode 100644 index 0000000..cd66720 --- /dev/null +++ b/python-tornado/examples/publish-example.py @@ -0,0 +1,44 @@ +## 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.0 Real-time Push Cloud API +## ----------------------------------- + +import sys +import tornado +sys.path.append('../') +from Pubnub import Pubnub + +publish_key   = len(sys.argv) > 1 and sys.argv[1] or 'demo' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' +secret_key    = len(sys.argv) > 3 and sys.argv[3] or 'demo' +cipher_key    = len(sys.argv) > 4 and sys.argv[4] or '' ##(Cipher key is Optional) +ssl_on        = len(sys.argv) > 5 and bool(sys.argv[5]) or False + +## ----------------------------------------------------------------------- +## Initiate Pubnub State +## ----------------------------------------------------------------------- +pubnub = Pubnub( publish_key, subscribe_key, secret_key,cipher_key, ssl_on ) +crazy  = 'hello_world' + +## ----------------------------------------------------------------------- +## History Example +## ----------------------------------------------------------------------- +def history_complete(messages): +    print(messages) + +pubnub.history( { +   'channel'  : crazy, +   'limit'    : 10, +   'callback' : history_complete +}) + +## ----------------------------------------------------------------------- +## IO Event Loop +## ----------------------------------------------------------------------- +tornado.ioloop.IOLoop.instance().start() diff --git a/python-tornado/examples/subscribe-example.py b/python-tornado/examples/subscribe-example.py new file mode 100644 index 0000000..c819f94 --- /dev/null +++ b/python-tornado/examples/subscribe-example.py @@ -0,0 +1,60 @@ +## 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.1 Real-time Push Cloud API +## ----------------------------------- + +import sys +import tornado +sys.path.append('../') +from Pubnub import Pubnub + +publish_key   = len(sys.argv) > 1 and sys.argv[1] or 'demo' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' +secret_key    = len(sys.argv) > 3 and sys.argv[3] or 'demo' +cipher_key    = len(sys.argv) > 4 and sys.argv[4] or '' ##(Cipher key is Optional) +ssl_on        = len(sys.argv) > 5 and bool(sys.argv[5]) or False + +## ----------------------------------------------------------------------- +## Initiate Pubnub State +## ----------------------------------------------------------------------- +pubnub = Pubnub( publish_key, subscribe_key, secret_key,cipher_key, ssl_on ) +crazy  = 'hello_world' + +## ----------------------------------------------------------------------- +## Publish Example +## ----------------------------------------------------------------------- +def publish_complete(info): +    print(info) + +## Publish string +pubnub.publish({ +    'channel' : crazy, +    'message' : 'Hello World!', +    'callback' : publish_complete +}) + +## Publish list +li = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] +pubnub.publish({ +    'channel' : crazy, +    'message' : li, +    'callback' : publish_complete +}) + +## Publish Dictionary Object +pubnub.publish({ +    'channel' : crazy, +    'message' : { 'some_key' : 'some_val' }, +    'callback' : publish_complete +}) + +## ----------------------------------------------------------------------- +## IO Event Loop +## ----------------------------------------------------------------------- +tornado.ioloop.IOLoop.instance().start() diff --git a/python-tornado/examples/uuid-example.py b/python-tornado/examples/uuid-example.py new file mode 100644 index 0000000..f24671b --- /dev/null +++ b/python-tornado/examples/uuid-example.py @@ -0,0 +1,28 @@ +## 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.1 Real-time Push Cloud API +## ----------------------------------- + +import sys +import tornado +sys.path.append('../') +from Pubnub import Pubnub + +## ----------------------------------------------------------------------- +## Initiate Pubnub State +## ----------------------------------------------------------------------- +pubnub = Pubnub( "", "", "", False ) + +## ----------------------------------------------------------------------- +## UUID Example +## ----------------------------------------------------------------------- +uuid = pubnub.uuid() +print "UUID: " +print uuid + diff --git a/python-tornado/tests/benchmark.py b/python-tornado/tests/benchmark.py new file mode 100644 index 0000000..5f9b5e3 --- /dev/null +++ b/python-tornado/tests/benchmark.py @@ -0,0 +1,96 @@ +## 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.1 Real-time Push Cloud API +## ----------------------------------- + +import sys +import datetime +import tornado +sys.path.append('../') +from Pubnub import Pubnub + +publish_key   = len(sys.argv) > 1 and sys.argv[1] or 'demo' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' +secret_key    = len(sys.argv) > 3 and sys.argv[3] or 'demo' +cipher_key    = len(sys.argv) > 4 and sys.argv[4] or 'demo' +ssl_on        = len(sys.argv) > 5 and bool(sys.argv[5]) or False +origin        = len(sys.argv) > 6 and sys.argv[6] or 'pubsub.pubnub.com' + + +## ----------------------------------------------------------------------- +## Initiat Class +## ----------------------------------------------------------------------- +pubnub = Pubnub( +    publish_key, +    subscribe_key, +    secret_key = secret_key, +    cipher_key = cipher_key, +    ssl_on = ssl_on, +    origin = origin +) +crazy  = ' ~`!@#$%^&*( 顶顅 Ȓ)+=[]\\{}|;\':",./<>?abcd' + +## ----------------------------------------------------------------------- +## BENCHMARK +## ----------------------------------------------------------------------- +def connected() : +    pubnub.publish({ +        'channel' : crazy, +        'message' : { 'Info' : 'Connected!' } +    }) + +trips = { 'last' : None, 'current' : None, 'max' : 0, 'avg' : 0 } + +def received(message): +    current_trip = trips['current'] = str(datetime.datetime.now())[0:19] +    last_trip    = trips['last']    = str( +        datetime.datetime.now() - datetime.timedelta(seconds=1) +    )[0:19] + +    ## New Trip Span (1 Second) +    if not trips.has_key(current_trip) : +        trips[current_trip] = 0 + +        ## Average +        if trips.has_key(last_trip): +            trips['avg'] = (trips['avg'] + trips[last_trip]) / 2 + +    ## Increment Trip Counter +    trips[current_trip] = trips[current_trip] + 1 + +    ## Update Max +    if trips[current_trip] > trips['max'] : +        trips['max'] = trips[current_trip] + + +    print(message) + +    pubnub.publish({ +        'channel' : crazy, +        'message' : current_trip     + +            " Trip: "                + +            str(trips[current_trip]) + +            " MAX: "                 + +            str(trips['max'])        + +            "/sec "                  + +            " AVG: "                 + +            str(trips['avg'])        + +            "/sec" +    }) + +pubnub.subscribe({ +    'channel'  : crazy, +    'connect'  : connected, +    'callback' : received +}) + +## ----------------------------------------------------------------------- +## IO Event Loop +## ----------------------------------------------------------------------- +pubnub.start() diff --git a/python-tornado/tests/delivery.py b/python-tornado/tests/delivery.py new file mode 100644 index 0000000..f3633e6 --- /dev/null +++ b/python-tornado/tests/delivery.py @@ -0,0 +1,161 @@ +## 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.1 Real-time Push Cloud API +## ----------------------------------- + +import sys +import datetime +import time +import math + +sys.path.append('../') +from Pubnub import Pubnub + +## ----------------------------------------------------------------------- +## Configuration +## ----------------------------------------------------------------------- +publish_key   = len(sys.argv) > 1 and sys.argv[1] or 'demo' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' +secret_key    = len(sys.argv) > 3 and sys.argv[3] or 'demo' +cipher_key    = len(sys.argv) > 4 and sys.argv[4] or 'demo' +ssl_on        = len(sys.argv) > 5 and bool(sys.argv[5]) or False +origin        = len(sys.argv) > 6 and sys.argv[6] or 'pubsub.pubnub.com' + +## ----------------------------------------------------------------------- +## Analytics +## ----------------------------------------------------------------------- +analytics = { +    'publishes'            : 0,   ## Total Send Requests +    'received'             : 0,   ## Total Received Messages (Deliveries) +    'queued'               : 0,   ## Total Unreceived Queue (UnDeliveries) +    'successful_publishes' : 0,   ## Confirmed Successful Publish Request +    'failed_publishes'     : 0,   ## Confirmed UNSuccessful Publish Request +    'failed_deliveries'    : 0,   ## (successful_publishes - received) +    'deliverability'       : 0    ## Percentage Delivery +} + +trips = { +    'last'    : None, +    'current' : None, +    'max'     : 0, +    'avg'     : 0 +} + +## ----------------------------------------------------------------------- +## Initiat Class +## ----------------------------------------------------------------------- +channel = 'deliverability-' + str(time.time()) +pubnub  = Pubnub( +    publish_key, +    subscribe_key, +    secret_key = secret_key, +    cipher_key = cipher_key, +    ssl_on = ssl_on, +    origin = origin +) + +## ----------------------------------------------------------------------- +## BENCHMARK +## ----------------------------------------------------------------------- +def publish_sent(info = None): +    if info and info[0]: analytics['successful_publishes']   += 1 +    else:                analytics['failed_publishes']       += 1 + +    analytics['publishes'] += 1 +    analytics['queued']    += 1 + +    pubnub.timeout( send, 0.1 ) + +def send(): +    if analytics['queued'] > 100: +        analytics['queued'] -= 10 +        return pubnub.timeout( send, 10 ) + +    pubnub.publish({ +        'channel'  : channel, +        'callback' : publish_sent, +        'message'  : "1234567890" +    }) + +def received(message): +    analytics['queued']   -= 1 +    analytics['received'] += 1 +    current_trip = trips['current'] = str(datetime.datetime.now())[0:19] +    last_trip    = trips['last']    = str( +        datetime.datetime.now() - datetime.timedelta(seconds=1) +    )[0:19] + +    ## New Trip Span (1 Second) +    if not trips.has_key(current_trip) : +        trips[current_trip] = 0 + +        ## Average +        if trips.has_key(last_trip): +            trips['avg'] = (trips['avg'] + trips[last_trip]) / 2 + +    ## Increment Trip Counter +    trips[current_trip] = trips[current_trip] + 1 + +    ## Update Max +    if trips[current_trip] > trips['max'] : +        trips['max'] = trips[current_trip] + +def show_status(): +    ## Update Failed Deliveries +    analytics['failed_deliveries'] = \ +        analytics['successful_publishes'] \ +        - analytics['received'] + +    ## Update Deliverability +    analytics['deliverability'] = ( +        float(analytics['received']) / \ +        float(analytics['successful_publishes'] or 1.0) +    ) * 100.0 + +    ## Print Display +    print( ( +       "max:%(max)03d/sec  "                  + \ +       "avg:%(avg)03d/sec  "                  + \ +       "pubs:%(publishes)05d  "               + \ +       "received:%(received)05d  "            + \ +       "spub:%(successful_publishes)05d  "    + \ +       "fpub:%(failed_publishes)05d  "        + \ +       "failed:%(failed_deliveries)05d  "     + \ +       "queued:%(queued)03d  "                + \ +       "delivery:%(deliverability)03f%%  "    + \ +       "" +    ) % { +        'max'                  : trips['max'], +        'avg'                  : trips['avg'], +        'publishes'            : analytics['publishes'], +        'received'             : analytics['received'], +        'successful_publishes' : analytics['successful_publishes'], +        'failed_publishes'     : analytics['failed_publishes'], +        'failed_deliveries'    : analytics['failed_deliveries'], +        'publishes'            : analytics['publishes'], +        'deliverability'       : analytics['deliverability'], +        'queued'               : analytics['queued'] +    } ) +    pubnub.timeout( show_status, 1 ) + +def connected(): +    show_status() +    pubnub.timeout( send, 1 ) + +print( "Connected: %s\n" % origin ) +pubnub.subscribe({ +    'channel'  : channel, +    'connect'  : connected, +    'callback' : received +}) + +## ----------------------------------------------------------------------- +## IO Event Loop +## ----------------------------------------------------------------------- +pubnub.start() diff --git a/python-tornado/tests/unit-test.py b/python-tornado/tests/unit-test.py new file mode 100644 index 0000000..f593d11 --- /dev/null +++ b/python-tornado/tests/unit-test.py @@ -0,0 +1,224 @@ +## 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/ + +## TODO Tests +## +## - wait 20 minutes, send a message, receive and success. +## -  +## -  +##  +##  + +## ----------------------------------- +## PubNub 3.1 Real-time Push Cloud API +## ----------------------------------- + +import sys +sys.path.append('../') +from Pubnub import Pubnub + +publish_key   = len(sys.argv) > 1 and sys.argv[1] or 'demo' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' +secret_key    = len(sys.argv) > 3 and sys.argv[3] or None  +cipher_key    = len(sys.argv) > 4 and sys.argv[4] or None +ssl_on        = len(sys.argv) > 5 and bool(sys.argv[5]) or False + +## ----------------------------------------------------------------------- +## Command Line Options Supplied PubNub +## ----------------------------------------------------------------------- +pubnub_user_supplied_options = Pubnub( +    publish_key,   ## OPTIONAL (supply None to disable) +    subscribe_key, ## REQUIRED +    secret_key,    ## OPTIONAL (supply None to disable) +    cipher_key,    ## OPTIONAL (supply None to disable) +    ssl_on         ## OPTIONAL (supply None to disable) +) + +## ----------------------------------------------------------------------- +## High Security PubNub +## ----------------------------------------------------------------------- +pubnub_high_security = Pubnub( +    ## Publish Key +    'pub-c-a30c030e-9f9c-408d-be89-d70b336ca7a0', + +    ## Subscribe Key +    'sub-c-387c90f3-c018-11e1-98c9-a5220e0555fd', + +    ## Secret Key +    'sec-c-MTliNDE0NTAtYjY4Ni00MDRkLTllYTItNDhiZGE0N2JlYzBl', + +    ## Cipher Key +    'YWxzamRmbVjFaa05HVnGFqZHM3NXRBS73jxmhVMkjiwVVXV1d5UrXR1JLSkZFRr'+ +    'WVd4emFtUm1iR0TFpUZvbiBoYXMgYmVlbxWkhNaF3uUi8kM0YkJTEVlZYVFjBYi'+ +    'jFkWFIxSkxTa1pGUjd874hjklaTFpUwRVuIFNob3VsZCB5UwRkxUR1J6YVhlQWa'+ +    'V1ZkNGVH32mDkdho3pqtRnRVbTFpUjBaeGUgYXNrZWQtZFoKjda40ZWlyYWl1eX'+ +    'U4RkNtdmNub2l1dHE2TTA1jd84jkdJTbFJXYkZwWlZtRnKkWVrSRhhWbFpZVmFz'+ +    'c2RkZmTFpUpGa1dGSXhTa3hUYTFwR1Vpkm9yIGluZm9ybWFNfdsWQdSiiYXNWVX'+ +    'RSblJWYlRGcFVqQmFlRmRyYUU0MFpXbHlZV2wxZVhVNFJrTnR51YjJsMWRIRTJU'+ +    'W91ciBpbmZvcm1hdGliBzdWJtaXR0ZWQb3UZSBhIHJlc3BvbnNlLCB3ZWxsIHJl'+ +    'VEExWdHVybiB0am0aW9uIb24gYXMgd2UgcG9zc2libHkgY2FuLuhcFe24ldWVns'+ +    'dSaTFpU3hVUjFKNllWaFdhRmxZUWpCaQo34gcmVxdWlGFzIHNveqQl83snBfVl3', + +    ## 2048bit SSL ON - ENABLED TRUE +    True +) + +## ----------------------------------------------------------------------- +## Channel | Message Test Data (UTF-8) +## ----------------------------------------------------------------------- +crazy            = ' ~`â¦â§!@#$%^&*(顶顅Ȓ)+=[]\\{}|;\':",./<>?abcd' +many_channels    = [ str(x) + '-many_channel_test' for x in range(10) ] +runthroughs      = 0 +planned_tests    = 2 +delivery_retries = 0 +max_retries      = 10 + +## ----------------------------------------------------------------------- +## Unit Test Function +## ----------------------------------------------------------------------- +def test( trial, name ) : +    if trial : print( 'PASS: ' + name ) +    else :     print( '- FAIL - ' + name ) + +def test_pubnub(pubnub): +    global runthroughs, planned_tests, delivery_retries, max_retries + +    ## ----------------------------------------------------------------------- +    ## Many Channels +    ## ----------------------------------------------------------------------- +    def phase2(): +        status = { +            'sent'        : 0, +            'received'    : 0, +            'connections' : 0 +        } + +        def received( message, chan ): +            global runthroughs + +            test( status['received'] <= status['sent'], 'many sends' ) +            status['received'] += 1 +            pubnub.unsubscribe({ 'channel' : chan }) +            if status['received'] == len(many_channels): +                runthroughs += 1 +                if runthroughs == planned_tests: pubnub.stop() + +        def publish_complete( info, chan ): +            global delivery_retries, max_retries +            status['sent'] += 1 +            test( info, 'publish complete' ) +            test( info and len(info) > 2, 'publish response' ) +            if not info[0]: +                delivery_retries += 1 +                if max_retries > delivery_retries: sendit(chan) + +        def sendit(chan): +            tchan = chan +            pubnub.publish({ +                'channel'  : chan, +                'message'  : "Hello World", +                'callback' : (lambda msg:publish_complete( msg, tchan )) +            }) + +        def connected(chan): +            status['connections'] += 1 +            sendit(chan) + +        def delivered(info): +            if info and info[0]: status['sent'] += 1 + +        def subscribe(chan): +            pubnub.subscribe({ +                'channel'  : chan, +                'connect'  : (lambda:connected(chan+'')), +                'callback' : (lambda msg:received( msg, chan )) +            }) + +        ## Subscribe All Channels +        for chan in many_channels: subscribe(chan) +         +    ## ----------------------------------------------------------------------- +    ## Time Example +    ## ----------------------------------------------------------------------- +    def time_complete(timetoken): +        test( timetoken, 'timetoken fetch' ) +        test( isinstance( timetoken, int ), 'timetoken int type' ) + +    pubnub.time({ 'callback' : time_complete }) + +    ## ----------------------------------------------------------------------- +    ## Publish Example +    ## ----------------------------------------------------------------------- +    def publish_complete(info): +        test( info, 'publish complete' ) +        test( info and len(info) > 2, 'publish response' ) + +        pubnub.history( { +            'channel'  : crazy, +            'limit'    : 10, +            'callback' : history_complete +        }) + +    ## ----------------------------------------------------------------------- +    ## History Example +    ## ----------------------------------------------------------------------- +    def history_complete(messages): +        test( messages and len(messages) > 0, 'history' ) +        test( messages, 'history' ) + + +    pubnub.publish({ +        'channel'  : crazy, +        'message'  : "Hello World", +        'callback' : publish_complete +    }) + +    ## ----------------------------------------------------------------------- +    ## Subscribe Example +    ## ----------------------------------------------------------------------- +    def message_received(message): +        test( message, 'message received' ) +        pubnub.unsubscribe({ 'channel' : crazy }) + +        def done() : +            pubnub.unsubscribe({ 'channel' : crazy }) +            pubnub.publish({ +                'channel'  : crazy, +                'message'  : "Hello World", +                'callback' : (lambda x:x) +            }) + +        def dumpster(message) : +            test( 0, 'never see this' ) + +        pubnub.subscribe({ +            'channel'  : crazy, +            'connect'  : done, +            'callback' : dumpster +        }) + +    def connected() : +        pubnub.publish({ +            'channel' : crazy, +            'message' : { 'Info' : 'Connected!' } +        }) + +    pubnub.subscribe({ +        'channel'  : crazy, +        'connect'  : connected, +        'callback' : message_received +    }) + +    phase2() + +## ----------------------------------------------------------------------- +## Run Tests +## ----------------------------------------------------------------------- +test_pubnub(pubnub_user_supplied_options) +test_pubnub(pubnub_high_security) +pubnub_high_security.start() + | 
