diff options
38 files changed, 4103 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() + diff --git a/python-twisted/Pubnub.py b/python-twisted/Pubnub.py new file mode 100644 index 0000000..3c3f4b1 --- /dev/null +++ b/python-twisted/Pubnub.py @@ -0,0 +1,487 @@ +## 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 json +import time +import hashlib +import urllib2 +import uuid +try: +    from hashlib import sha256 +    digestmod = sha256 +except ImportError: +    import Crypto.Hash.SHA256 as digestmod +    sha256 = digestmod.new +import hmac +from twisted.internet import reactor +from twisted.internet.defer import Deferred +from twisted.internet.protocol import Protocol +from twisted.web.client import Agent +from twisted.web.client import HTTPConnectionPool +from twisted.web.http_headers import Headers +from PubnubCrypto import PubnubCrypto +import gzip +import zlib + +pnconn_pool = HTTPConnectionPool(reactor) +pnconn_pool.maxPersistentPerHost    = 100 +pnconn_pool.cachedConnectionTimeout = 310 + +class Pubnub(): + +    def start(self): reactor.run() +    def stop(self):  reactor.stop() +    def timeout( self, callback, delay ): +        reactor.callLater( 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 +        }) + +        """ +        ## Capture Callback +        if args.has_key('callback'): callback = args['callback'] +        else: callback = lambda x : x + +        ## Fail if bad input. +        if not (args['channel'] and args['message']): +            callback([ 0, 'Missing Channel or Message', 0 ]) +            return False + +        ## Capture User Input +        channel = str(args['channel']) +        message = args['message'] + +        if self.cipher_key : +            pc = PubnubCrypto() +            out = [] +            if type( message ) == type(list()): +                for item in message: +                    encryptItem = pc.encrypt(self.cipher_key, item ).rstrip() +                    out.append(encryptItem) +                message = json.dumps(out) +            elif type( message ) == type(dict()): +                outdict = {} +                for k, item in message.iteritems(): +                    encryptItem = pc.encrypt(self.cipher_key, item ).rstrip() +                    outdict[k] = encryptItem +                    out.append(outdict) +                message = json.dumps(out[0]) +            else: +                message = json.dumps(pc.encrypt(self.cipher_key, message).replace('\n','')) +        else : +            message = json.dumps(args['message']) + +        def publish_response(info): +            callback(info or [0, 'Disconnected', 0]); + +        ## Sign Message +        if self.secret_key : +            hashObject = sha256() +            hashObject.update(self.secret_key) +            hashedSecret = hashObject.hexdigest() +            hash = hmac.HMAC(hashedSecret, '/'.join([ +                    self.publish_key, +                    self.subscribe_key, +                    self.secret_key, +                    channel, +                    message +                ]), digestmod=digestmod) +            signature = hash.hexdigest()         +        else : +            signature = '0' + +        ## Send Message +        return self._request([ +            'publish', +            self.publish_key, +            self.subscribe_key, +            signature, +            channel, +            '0', +            message +        ], publish_response ) + + +    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 : +            return 'Missing Channel.' + +        ## Fail if missing callback +        if not 'callback' in args : +            return 'Missing Callback.' + +        ## 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'] : +            return "Already Connected" + +        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: +                            reactor.callLater( 1, substabizel ) +                            return errorback("Lost Network Connection") +                        else: +                            reactor.callLater( 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 ) +                     else : +                          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 : +                reactor.callLater( 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 : +            return 'Missing Channel' + +        ## Get History +        pc = PubnubCrypto() +        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) : +            if not response: return 0 +            args['callback'](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 ) : +        global pnconn_pool + +        ## 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] +        agent       = Agent( +            reactor, +            self.ssl and None or pnconn_pool, +            connectTimeout=30 +        ) +        request     = agent.request( 'GET', url, Headers({ +            'V'               : ['3.1'], +            'User-Agent'      : ['Python-Twisted'], +            'Accept-Encoding' : ['gzip'] +        }), None ) + +        self.resulting_is = str() +        def received(response): +            headerlist = list(response.headers.getAllRawHeaders()) +            for item in headerlist: +                if( item[0] == "Content-Encoding"): +                    if type(item[1]) == type(list()): +                        for subitem in item[1]: +                            self.resulting_is = subitem +                    elif type(item[1]) == type(str()): +                        self.resulting_is = item[1] + +            finished = Deferred() +            response.deliverBody(PubNubResponse(finished)) +            return finished + +        def complete(data): +            if ( type(data) == type(str()) ): +                if self.resulting_is: +                    d = zlib.decompressobj(16+zlib.MAX_WBITS) + +            try     :   data = d.decompress(data) # try/catch here, pass through if except +            except  :   data = data + +            try    : obj = json.loads(data) +            except : obj = None + +            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) + +        request.addCallback(received) +        request.addBoth(complete) + + + +class PubNubResponse(Protocol): +    def __init__( self, finished ): +        self.finished = finished + +    def dataReceived( self, bytes ): +            self.finished.callback(bytes) + diff --git a/python-twisted/Pubnub.pyc b/python-twisted/Pubnub.pycBinary files differ new file mode 100644 index 0000000..94d6ecc --- /dev/null +++ b/python-twisted/Pubnub.pyc diff --git a/python-twisted/PubnubCrypto.py b/python-twisted/PubnubCrypto.py new file mode 100644 index 0000000..744f2d3 --- /dev/null +++ b/python-twisted/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-twisted/PubnubCrypto.pyc b/python-twisted/PubnubCrypto.pycBinary files differ new file mode 100644 index 0000000..a349424 --- /dev/null +++ b/python-twisted/PubnubCrypto.pyc diff --git a/python-twisted/README b/python-twisted/README new file mode 100644 index 0000000..5f9b350 --- /dev/null +++ b/python-twisted/README @@ -0,0 +1,118 @@ +## --------------------------------------------------- +## +## YOU MUST HAVE A PUBNUB ACCOUNT TO USE THE API. +## http://www.pubnub.com/account +## +## ---------------------------------------------------- + +## ---------------------------------------------------- +## PubNub 3.1 Real-time Cloud Push API - PYTHON TWISTED +## ---------------------------------------------------- +## +## www.pubnub.com - PubNub Real-time Push Service in the Cloud.  +## http://github.com/pubnub/pubnub-api/tree/master/python-twisted/ +## +## 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. + +## ---------------------------------------------------- +## Python Twisted Setup +## ---------------------------------------------------- +## Download BZ2 archive from http://twistedmatrix.com/ +##  +## > tar xvfj Twisted-12.1.0.tar.bz2 +## > cd Twisted-12.1.0 +## > sudo python setup.py install +##  + +## ---------------------------------------------------- +## 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! +## +## reactor.run() ## IMPORTANT! +## + +## ----------------------------------------------------------------------- +## Subscribe Example +## ----------------------------------------------------------------------- + +def connected() : +    ## ----------------------------------------------------------------------- +    ## Publish Example +    ## ----------------------------------------------------------------------- +    def publish_complete(info): +        print(info) + +    pubnub.publish({ +        'channel' : "my-twisted-channel", +        'message' : { +            'some_text' : 'Hello World!' +        }, +        'callback' : publish_complete +    }) + +def message_received(message): +    print(message) + +pubnub.subscribe({ +    'channel'  : "my-twisted-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-twisted-channel", +    'limit'    : 10, +    'callback' : history_complete +}) + +## ----------------------------------------------------------------------- +## UUID Example +## ----------------------------------------------------------------------- +uuid = pubnub.uuid() +print "UUID" +print uuid + +## ----------------------------------------------------------------------- +## IO Event Loop +## ----------------------------------------------------------------------- +reactor.run() diff --git a/python-twisted/examples/history-example.py b/python-twisted/examples/history-example.py new file mode 100644 index 0000000..31b8edb --- /dev/null +++ b/python-twisted/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.1 Real-time Push Cloud API +## ----------------------------------- + +import sys +from twisted.internet import reactor +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 +## ----------------------------------------------------------------------- +reactor.run() diff --git a/python-twisted/examples/publish-example.py b/python-twisted/examples/publish-example.py new file mode 100644 index 0000000..4a5baf6 --- /dev/null +++ b/python-twisted/examples/publish-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 +from twisted.internet import reactor +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 +## ----------------------------------------------------------------------- +reactor.run() diff --git a/python-twisted/examples/subscribe-example.py b/python-twisted/examples/subscribe-example.py new file mode 100644 index 0000000..994e7e3 --- /dev/null +++ b/python-twisted/examples/subscribe-example.py @@ -0,0 +1,50 @@ +## 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 +from twisted.internet import reactor +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 None +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' + +## ----------------------------------------------------------------------- +## Subscribe Example +## ----------------------------------------------------------------------- +def message_received(message): +    print(message) + +def connected() : +    pubnub.publish({ +        'channel' : crazy, +        'message' : { 'Info' : 'Connected!' } +    }) + +pubnub.subscribe({ +    'channel'  : crazy, +    'connect'  : connected, +    'callback' : message_received +}) + +## ----------------------------------------------------------------------- +## IO Event Loop +## ----------------------------------------------------------------------- +reactor.run() diff --git a/python-twisted/examples/uuid-example.py b/python-twisted/examples/uuid-example.py new file mode 100644 index 0000000..94840e0 --- /dev/null +++ b/python-twisted/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 +from twisted.internet import reactor +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-twisted/tests/benchmark.py b/python-twisted/tests/benchmark.py new file mode 100644 index 0000000..d4d6d80 --- /dev/null +++ b/python-twisted/tests/benchmark.py @@ -0,0 +1,87 @@ +## 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 datetime +from twisted.internet import reactor +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 + +## ----------------------------------------------------------------------- +## Initiat Class +## ----------------------------------------------------------------------- +pubnub = Pubnub( publish_key, subscribe_key, secret_key, cipher_key, ssl_on ) +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 +## ----------------------------------------------------------------------- +reactor.run() diff --git a/python-twisted/tests/delivery.py b/python-twisted/tests/delivery.py new file mode 100644 index 0000000..dc6b9e2 --- /dev/null +++ b/python-twisted/tests/delivery.py @@ -0,0 +1,162 @@ +## 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' +origin = '184.72.9.220' + +## ----------------------------------------------------------------------- +## 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-twisted/tests/unit-test-full.py b/python-twisted/tests/unit-test-full.py new file mode 100644 index 0000000..f593d11 --- /dev/null +++ b/python-twisted/tests/unit-test-full.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() + diff --git a/python-twisted/tests/unit-test.py b/python-twisted/tests/unit-test.py new file mode 100644 index 0000000..843f939 --- /dev/null +++ b/python-twisted/tests/unit-test.py @@ -0,0 +1,107 @@ +## 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 +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 + +## ----------------------------------------------------------------------- +## Initiat Class +## ----------------------------------------------------------------------- +pubnub = Pubnub( publish_key, subscribe_key, secret_key, cipher_key, ssl_on ) +crazy  = ' ~`!@#$%^&*( 顶顅 Ȓ)+=[]\\{}|;\':",./<>?abcd' + +## --------------------------------------------------------------------------- +## Unit Test Function +## --------------------------------------------------------------------------- +def test( trial, name ) : +    if trial : +        print( 'PASS: ' + name ) +    else : +        print( 'FAIL: ' + name ) + +## ----------------------------------------------------------------------- +## Time Example +## ----------------------------------------------------------------------- +def time_complete(timestamp): +    print(timestamp) + +pubnub.time({ 'callback' : time_complete }) + +## ----------------------------------------------------------------------- +## History Example +## ----------------------------------------------------------------------- +def history_complete(messages): +    print(messages) + +pubnub.history( { +    'channel'  : crazy, +    'limit'    : 10, +    'callback' : history_complete +}) + +## ----------------------------------------------------------------------- +## Publish Example +## ----------------------------------------------------------------------- +def publish_complete(info): +    print(info) + +pubnub.publish({ +    'channel' : crazy, +    'message' :  {'one': 'Hello World! --> ɂ顶@#$%^&*()!', 'two': 'hello2'}, +    'callback' : publish_complete +}) + +## ----------------------------------------------------------------------- +## Subscribe Example +## ----------------------------------------------------------------------- +def message_received(message): +    print(message) +    print('Disconnecting...') +    pubnub.unsubscribe({ 'channel' : crazy }) + +    def done() : +        print('final connection, done :)') +        pubnub.unsubscribe({ 'channel' : crazy }) +        pubnub.stop() + +    def dumpster(message) : +        print('never see this') +        print(message) + +    print('reconnecting...') +    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 +}) +## ----------------------------------------------------------------------- +## IO Event Loop +## ----------------------------------------------------------------------- +pubnub.start() diff --git a/python/3.2/Pubnub.py b/python/3.2/Pubnub.py new file mode 100644 index 0000000..79086cf --- /dev/null +++ b/python/3.2/Pubnub.py @@ -0,0 +1,345 @@ +## 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 +## ----------------------------------- + +try: import json +except ImportError: import simplejson as json + +import time +import hashlib +import urllib2 +import uuid + +class Pubnub(): +    def __init__( +        self, +        publish_key, +        subscribe_key, +        secret_key = False, +        ssl_on = False, +        origin = 'pubsub.pubnub.com', +        pres_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.ssl           = ssl_on + +        if self.ssl : +            self.origin = 'https://' + self.origin +        else : +            self.origin = 'http://'  + self.origin +         +        self.uuid = pres_uuid or str(uuid.uuid4()) +         +        if not isinstance(self.uuid, basestring): +            raise AttributeError("pres_uuid must be a string") + +    def publish( self, args ) : +        """ +        #** +        #* 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) + +        """ +        ## Fail if bad input. +        if not (args['channel'] and args['message']) : +            return [ 0, 'Missing Channel or Message' ] + +        ## Capture User Input +        channel = str(args['channel']) +        message = json.dumps(args['message'], separators=(',',':')) + +        ## 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' + +        ## Send Message +        return self._request([ +            'publish', +            self.publish_key, +            self.subscribe_key, +            signature, +            channel, +            '0', +            message +        ]) + + +    def subscribe( self, args ) : +        """ +        #** +        #* Subscribe +        #* +        #* This is BLOCKING. +        #* Listen for a message on a channel. +        #* +        #* @param array args with channel and callback. +        #* @return false on fail, array on success. +        #** + +        ## Subscribe Example +        def receive(message) : +            print(message) +            return True + +        pubnub.subscribe({ +            'channel'  : 'hello_world', +            'callback' : receive  +        }) + +        """ + +        ## 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 + +        ## Begin Subscribe +        while True : + +            timetoken = 'timetoken' in args and args['timetoken'] or 0 +            try : +                ## Wait for Message +                response = self._request(self._encode([ +                    'subscribe', +                    subscribe_key, +                    channel, +                    '0', +                    str(timetoken) +                ])+['?uuid='+self.uuid], encode=False) + +                messages          = response[0] +                args['timetoken'] = response[1] + +                ## If it was a timeout +                if not len(messages) : +                    continue + +                ## Run user Callback and Reconnect if user permits. +                for message in messages : +                    if not callback(message) : +                        return + +            except Exception: +                time.sleep(1) + +        return True +     +    def presence( self, args ) : +        """ +        #** +        #* 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  +        }) +        """ + +        ## 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': callback}) +     +     +    def here_now( self, args ) : +        """ +        #** +        #* 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']) + +        """ +        channel = str(args['channel']) +         +        ## Fail if bad input. +        if not channel : +            raise Exception('Missing Channel') +            return False +         +        ## Get Presence Here Now +        return self._request([ +            'v2','presence', +            'sub_key', self.subscribe_key, +            'channel', channel +        ]); +         +         +    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 : +            raise Exception('Missing Channel') +            return False + +        ## Get History +        return self._request([ +            'history', +            self.subscribe_key, +            channel, +            '0', +            str(limit) +        ]); + + +    def time(self) : +        """ +        #** +        #* Time +        #* +        #* Timestamp from PubNub Cloud. +        #* +        #* @return int timestamp. +        #* + +        ## PubNub Server Time Example +        timestamp = pubnub.time() +        print(timestamp) + +        """ +        return self._request([ +            'time', +            '0' +        ])[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 _request( self, request, origin = None, encode = True ) : +        ## Build URL +        url = (origin or self.origin) + '/' + "/".join( +            encode and self._encode(request) or request +        ) + +        ## Send Request Expecting JSONP Response +        try: +            try: usock = urllib2.urlopen( url, None, 200 ) +            except TypeError: usock = urllib2.urlopen( url, None ) +            response = usock.read() +            usock.close() +            return json.loads( response ) +        except: +            return None + diff --git a/python/3.2/history-example.py b/python/3.2/history-example.py new file mode 100755 index 0000000..cedf69e --- /dev/null +++ b/python/3.2/history-example.py @@ -0,0 +1,12 @@ +from Pubnub import Pubnub + +## Initiat Class +pubnub = Pubnub( 'demo', 'demo', None, False ) + +## History Example +history = pubnub.history({ +    'channel' : 'hello_world', +    'limit'   : 1 +}) +print(history) + diff --git a/python/3.2/publish-example.py b/python/3.2/publish-example.py new file mode 100755 index 0000000..725df0b --- /dev/null +++ b/python/3.2/publish-example.py @@ -0,0 +1,14 @@ +from Pubnub import Pubnub + +## Initiate Class +pubnub = Pubnub( 'demo', 'demo', None, False ) + +## Publish Example +info = pubnub.publish({ +    'channel' : 'hello_world', +    'message' : { +        'some_text' : 'Hello my World' +    } +}) +print(info) + diff --git a/python/3.2/subscribe-example.py b/python/3.2/subscribe-example.py new file mode 100755 index 0000000..e458e2b --- /dev/null +++ b/python/3.2/subscribe-example.py @@ -0,0 +1,64 @@ +import sys +import threading +import time +import random +import string +from Pubnub import Pubnub + +## Initiate Class +pubnub = Pubnub( 'demo', 'demo', None, False ) + +print("My UUID is: "+pubnub.uuid) + +channel = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(20)) + +## Subscribe Example +def receive(message) : +    print(message) +    return False + +def pres_event(message): +    print(message) +    return False + +def subscribe(): +    print("Listening for messages on '%s' channel..." % channel) +    pubnub.subscribe({ +        'channel'  : channel, +        'callback' : receive  +    }) + +def presence(): +    print("Listening for presence events on '%s' channel..." % channel) +    pubnub.presence({ +        'channel'  : channel, +        'callback' : pres_event  +    }) + +def publish(): +    print("Publishing a test message on '%s' channel..." % channel) +    pubnub.publish({ +        'channel'  : channel, +        'message'  : { 'text':'foo bar' } +    }) + +pres_thread = threading.Thread(target=presence) +pres_thread.daemon=True +pres_thread.start() + +sub_thread = threading.Thread(target=subscribe) +sub_thread.daemon=True +sub_thread.start() + +time.sleep(3) + +publish() + + +print("waiting for subscribes and presence") +pres_thread.join() + +print pubnub.here_now({'channel':channel}) + +sub_thread.join() + diff --git a/python/3.2/unit-test.py b/python/3.2/unit-test.py new file mode 100755 index 0000000..88391a0 --- /dev/null +++ b/python/3.2/unit-test.py @@ -0,0 +1,77 @@ +## 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 +## ----------------------------------- + +from Pubnub import Pubnub +import sys + +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 +ssl_on        = len(sys.argv) > 4 and bool(sys.argv[4]) or False + + +## ----------------------------------------------------------------------- +## Initiat Class +## ----------------------------------------------------------------------- + +pubnub = Pubnub( publish_key, subscribe_key, secret_key, ssl_on ) +crazy  = ' ~`!@#$%^&*(顶顅Ȓ)+=[]\\{}|;\':",./<>?abcd' + +## --------------------------------------------------------------------------- +## Unit Test Function +## --------------------------------------------------------------------------- +def test( trial, name ) : +    if trial : +        print( 'PASS: ' + name ) +    else : +        print( 'FAIL: ' + name ) + +## ----------------------------------------------------------------------- +## Publish Example +## ----------------------------------------------------------------------- +pubish_success = pubnub.publish({ +    'channel' : crazy, +    'message' : crazy +}) +test( pubish_success[0] == 1, 'Publish First Message Success' ) + +## ----------------------------------------------------------------------- +## History Example +## ----------------------------------------------------------------------- +history = pubnub.history({ +    'channel' : crazy, +    'limit'   : 1 +}) +test( +    history[0].encode('utf-8') == crazy, +    'History Message: ' + history[0] +) +test( len(history) == 1, 'History Message Count' ) + +## ----------------------------------------------------------------------- +## PubNub Server Time Example +## ----------------------------------------------------------------------- +timestamp = pubnub.time() +test( timestamp > 0, 'PubNub Server Time: ' + str(timestamp) ) + +## ----------------------------------------------------------------------- +## Subscribe Example +## ----------------------------------------------------------------------- +def receive(message) : +    print(message) +    return True + +pubnub.subscribe({ +    'channel'  : crazy, +    'callback' : receive  +}) + + diff --git a/python/3.3/Pubnub.py b/python/3.3/Pubnub.py new file mode 100644 index 0000000..a3f4d6f --- /dev/null +++ b/python/3.3/Pubnub.py @@ -0,0 +1,401 @@ +## 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 +## ----------------------------------- + +try: import json +except ImportError: import simplejson as json + +import time +import hashlib +import urllib2 +import uuid + +class Pubnub(): +    def __init__( +        self, +        publish_key, +        subscribe_key, +        secret_key = False, +        ssl_on = False, +        origin = 'pubsub.pubnub.com', +        pres_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.ssl           = ssl_on + +        if self.ssl : +            self.origin = 'https://' + self.origin +        else : +            self.origin = 'http://'  + self.origin +         +        self.uuid = pres_uuid or str(uuid.uuid4()) +         +        if not isinstance(self.uuid, basestring): +            raise AttributeError("pres_uuid must be a string") + +    def publish( self, args ) : +        """ +        #** +        #* 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) + +        """ +        ## Fail if bad input. +        if not (args['channel'] and args['message']) : +            return [ 0, 'Missing Channel or Message' ] + +        ## Capture User Input +        channel = str(args['channel']) +        message = json.dumps(args['message'], separators=(',',':')) + +        ## 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' + +        ## Send Message +        return self._request([ +            'publish', +            self.publish_key, +            self.subscribe_key, +            signature, +            channel, +            '0', +            message +        ]) + + +    def subscribe( self, args ) : +        """ +        #** +        #* Subscribe +        #* +        #* This is BLOCKING. +        #* Listen for a message on a channel. +        #* +        #* @param array args with channel and callback. +        #* @return false on fail, array on success. +        #** + +        ## Subscribe Example +        def receive(message) : +            print(message) +            return True + +        pubnub.subscribe({ +            'channel'  : 'hello_world', +            'callback' : receive  +        }) + +        """ + +        ## 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 + +        ## Begin Subscribe +        while True : + +            timetoken = 'timetoken' in args and args['timetoken'] or 0 +            try : +                ## Wait for Message +                response = self._request(self._encode([ +                    'subscribe', +                    subscribe_key, +                    channel, +                    '0', +                    str(timetoken) +                ])+['?uuid='+self.uuid], encode=False) + +                messages          = response[0] +                args['timetoken'] = response[1] + +                ## If it was a timeout +                if not len(messages) : +                    continue + +                ## Run user Callback and Reconnect if user permits. +                for message in messages : +                    if not callback(message) : +                        return + +            except Exception: +                time.sleep(1) + +        return True +     +    def presence( self, args ) : +        """ +        #** +        #* 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  +        }) +        """ + +        ## 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': callback}) +     +     +    def here_now( self, args ) : +        """ +        #** +        #* 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']) + +        """ +        channel = str(args['channel']) +         +        ## Fail if bad input. +        if not channel : +            raise Exception('Missing Channel') +            return False +         +        ## Get Presence Here Now +        return self._request([ +            'v2','presence', +            'sub_key', self.subscribe_key, +            'channel', channel +        ]); +         +         +    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 : +            raise Exception('Missing Channel') +            return False + +        ## Get History +        return self._request([ +            'history', +            self.subscribe_key, +            channel, +            '0', +            str(limit) +        ]); + +    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. +        #* + +        ## History Example +        history = pubnub.detailedHistory({ +            'channel' : 'hello_world', +            'count'   : 5 +        }) +        print(history) + +        """ +        ## Capture User Input +        channel = str(args['channel']) + +        params = []  +        count = 100     +         +        if args.has_key('count'): +            count = int(args['count']) + +        params.append('count' + '=' + str(count))     +         +        if args.has_key('reverse'): +            params.append('reverse' + '=' + str(args['reverse']).lower()) + +        if args.has_key('start'): +            params.append('start' + '=' + str(args['start'])) + +        if args.has_key('end'): +            params.append('end' + '=' + str(args['end'])) + +        ## Fail if bad input. +        if not channel : +            raise Exception('Missing Channel') +            return False + +        ## Get History +        return self._request([ +            'v2', +            'history', +            'sub-key', +            self.subscribe_key, +            'channel', +            channel, +        ],params=params); + +    def time(self) : +        """ +        #** +        #* Time +        #* +        #* Timestamp from PubNub Cloud. +        #* +        #* @return int timestamp. +        #* + +        ## PubNub Server Time Example +        timestamp = pubnub.time() +        print(timestamp) + +        """ +        return self._request([ +            'time', +            '0' +        ])[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 _request( self, request, origin = None, encode = True, params = None ) : +        ## Build URL +        url = (origin or self.origin) + '/' + "/".join( +            encode and self._encode(request) or request +        ) +        ## Add query params +        if params is not None and len(params) > 0: +            url = url + "?" + "&".join(params) + +        ## Send Request Expecting JSONP Response +        try: +            try: usock = urllib2.urlopen( url, None, 200 ) +            except TypeError: usock = urllib2.urlopen( url, None ) +            response = usock.read() +            usock.close() +            return json.loads( response ) +        except: +            return None + diff --git a/python/3.3/Pubnub.pyc b/python/3.3/Pubnub.pycBinary files differ new file mode 100644 index 0000000..76bebc4 --- /dev/null +++ b/python/3.3/Pubnub.pyc diff --git a/python/3.3/detailed-history-unit-test.py b/python/3.3/detailed-history-unit-test.py new file mode 100755 index 0000000..2169e52 --- /dev/null +++ b/python/3.3/detailed-history-unit-test.py @@ -0,0 +1,134 @@ +## 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 +## ----------------------------------- + +from Pubnub import Pubnub +import unittest2 as unittest +import sys + + +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 +ssl_on = len(sys.argv) > 4 and bool(sys.argv[4]) or False +pubnub = Pubnub(publish_key, subscribe_key, secret_key, ssl_on) +crazy = ' ~`!@#$%^&*(顶顅Ȓ)+=[]\\{}|;\':",./<>?abcd' + + +class TestDetailedHistory(unittest.TestCase): +    total_msg = 10 +    channel = pubnub.time() +    starttime = None +    inputs = [] +    endtime = None +    slice_a = 8 +    slice_b = 2 +    slice_size = slice_a - slice_b + +    @classmethod +    def publish_msg(cls, start, end, offset): +        print 'Publishing messages' +        inputs = [] +        for i in range(start + offset, end + offset): +            message = str(i) + " " + crazy +            success = pubnub.publish({ +                                     'channel': cls.channel, +                                     'message': message, +                                     }) +            t = pubnub.time() +            inputs.append({'timestamp': t, 'message': message}) +            print 'Message # ', i, ' published' +        return inputs + +    @classmethod +    def setUpClass(cls): +        print 'Setting up context for Detailed History tests. Please wait ...' +        cls.starttime = pubnub.time() +        cls.inputs = cls.inputs + cls.publish_msg(0, cls.total_msg / 2, 0) +        cls.midtime = pubnub.time() +        cls.inputs = cls.inputs + cls.publish_msg( +            0, cls.total_msg / 2, cls.total_msg / 2) +        cls.endtime = pubnub.time() +        print 'Context setup for Detailed History tests. Now running tests' + +    def test_begin_to_end_count(self): +        count = 5 +        history = pubnub.detailedHistory({ +                                         'channel': self.__class__.channel, +                                         'start': self.__class__.starttime, +                                         'end': self.__class__.endtime, +                                         'count': count +                                         })[0] +        self.assertTrue(len(history) == count and history[-1].encode( +            'utf-8') == self.__class__.inputs[count - 1]['message']) + +    def test_end_to_begin_count(self): +        count = 5 +        history = pubnub.detailedHistory({ +                                         'channel': self.__class__.channel, +                                         'start': self.__class__.endtime, +                                         'end': self.__class__.starttime, +                                         'count': count +                                         })[0] +        self.assertTrue(len(history) == count and history[-1] +            .encode('utf-8') == self.__class__.inputs[-1]['message']) + +    def test_start_reverse_true(self): +        history = pubnub.detailedHistory({ +                                         'channel': self.__class__.channel, +                                         'start': self.__class__.midtime, +                                         'reverse': True +                                         })[0] +        self.assertTrue(len(history) == self.__class__.total_msg / 2) +        expected_msg = self.__class__.inputs[-1]['message'] +        self.assertTrue(history[-1].encode('utf-8') == expected_msg) + +    def test_start_reverse_false(self): +        history = pubnub.detailedHistory({ +                                         'channel': self.__class__.channel, +                                         'start': self.__class__.midtime, +                                         })[0] +        self.assertTrue(history[0].encode('utf-8') +                        == self.__class__.inputs[0]['message']) + +    def test_end_reverse_true(self): +        history = pubnub.detailedHistory({ +                                         'channel': self.__class__.channel, +                                         'end': self.__class__.midtime, +                                         'reverse': True +                                         })[0] +        self.assertTrue(history[0].encode('utf-8') +                        == self.__class__.inputs[0]['message']) + +    def test_end_reverse_false(self): +        history = pubnub.detailedHistory({ +                                         'channel': self.__class__.channel, +                                         'end': self.__class__.midtime, +                                         })[0] +        self.assertTrue(len(history) == self.__class__.total_msg / 2) +        self.assertTrue(history[-1].encode('utf-8') +                        == self.__class__.inputs[-1]['message']) + +    def test_count(self): +        history = pubnub.detailedHistory({ +                                         'channel': self.__class__.channel, +                                         'count': 5 +                                         })[0] +        self.assertTrue(len(history) == 5) + +    def test_count_zero(self): +        history = pubnub.detailedHistory({ +                                         'channel': self.__class__.channel, +                                         'count': 0 +                                         })[0] +        self.assertTrue(len(history) == 0) + +if __name__ == '__main__': +    unittest.main() diff --git a/python/3.3/history-example.py b/python/3.3/history-example.py new file mode 100755 index 0000000..cedf69e --- /dev/null +++ b/python/3.3/history-example.py @@ -0,0 +1,12 @@ +from Pubnub import Pubnub + +## Initiat Class +pubnub = Pubnub( 'demo', 'demo', None, False ) + +## History Example +history = pubnub.history({ +    'channel' : 'hello_world', +    'limit'   : 1 +}) +print(history) + diff --git a/python/3.3/publish-example.py b/python/3.3/publish-example.py new file mode 100755 index 0000000..725df0b --- /dev/null +++ b/python/3.3/publish-example.py @@ -0,0 +1,14 @@ +from Pubnub import Pubnub + +## Initiate Class +pubnub = Pubnub( 'demo', 'demo', None, False ) + +## Publish Example +info = pubnub.publish({ +    'channel' : 'hello_world', +    'message' : { +        'some_text' : 'Hello my World' +    } +}) +print(info) + diff --git a/python/3.3/subscribe-example.py b/python/3.3/subscribe-example.py new file mode 100755 index 0000000..e458e2b --- /dev/null +++ b/python/3.3/subscribe-example.py @@ -0,0 +1,64 @@ +import sys +import threading +import time +import random +import string +from Pubnub import Pubnub + +## Initiate Class +pubnub = Pubnub( 'demo', 'demo', None, False ) + +print("My UUID is: "+pubnub.uuid) + +channel = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(20)) + +## Subscribe Example +def receive(message) : +    print(message) +    return False + +def pres_event(message): +    print(message) +    return False + +def subscribe(): +    print("Listening for messages on '%s' channel..." % channel) +    pubnub.subscribe({ +        'channel'  : channel, +        'callback' : receive  +    }) + +def presence(): +    print("Listening for presence events on '%s' channel..." % channel) +    pubnub.presence({ +        'channel'  : channel, +        'callback' : pres_event  +    }) + +def publish(): +    print("Publishing a test message on '%s' channel..." % channel) +    pubnub.publish({ +        'channel'  : channel, +        'message'  : { 'text':'foo bar' } +    }) + +pres_thread = threading.Thread(target=presence) +pres_thread.daemon=True +pres_thread.start() + +sub_thread = threading.Thread(target=subscribe) +sub_thread.daemon=True +sub_thread.start() + +time.sleep(3) + +publish() + + +print("waiting for subscribes and presence") +pres_thread.join() + +print pubnub.here_now({'channel':channel}) + +sub_thread.join() + diff --git a/python/3.3/unit-test.py b/python/3.3/unit-test.py new file mode 100755 index 0000000..88391a0 --- /dev/null +++ b/python/3.3/unit-test.py @@ -0,0 +1,77 @@ +## 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 +## ----------------------------------- + +from Pubnub import Pubnub +import sys + +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 +ssl_on        = len(sys.argv) > 4 and bool(sys.argv[4]) or False + + +## ----------------------------------------------------------------------- +## Initiat Class +## ----------------------------------------------------------------------- + +pubnub = Pubnub( publish_key, subscribe_key, secret_key, ssl_on ) +crazy  = ' ~`!@#$%^&*(顶顅Ȓ)+=[]\\{}|;\':",./<>?abcd' + +## --------------------------------------------------------------------------- +## Unit Test Function +## --------------------------------------------------------------------------- +def test( trial, name ) : +    if trial : +        print( 'PASS: ' + name ) +    else : +        print( 'FAIL: ' + name ) + +## ----------------------------------------------------------------------- +## Publish Example +## ----------------------------------------------------------------------- +pubish_success = pubnub.publish({ +    'channel' : crazy, +    'message' : crazy +}) +test( pubish_success[0] == 1, 'Publish First Message Success' ) + +## ----------------------------------------------------------------------- +## History Example +## ----------------------------------------------------------------------- +history = pubnub.history({ +    'channel' : crazy, +    'limit'   : 1 +}) +test( +    history[0].encode('utf-8') == crazy, +    'History Message: ' + history[0] +) +test( len(history) == 1, 'History Message Count' ) + +## ----------------------------------------------------------------------- +## PubNub Server Time Example +## ----------------------------------------------------------------------- +timestamp = pubnub.time() +test( timestamp > 0, 'PubNub Server Time: ' + str(timestamp) ) + +## ----------------------------------------------------------------------- +## Subscribe Example +## ----------------------------------------------------------------------- +def receive(message) : +    print(message) +    return True + +pubnub.subscribe({ +    'channel'  : crazy, +    'callback' : receive  +}) + + diff --git a/python/README b/python/README new file mode 100644 index 0000000..ba65e53 --- /dev/null +++ b/python/README @@ -0,0 +1,123 @@ +## --------------------------------------------------- +## +## YOU MUST HAVE A PUBNUB ACCOUNT TO USE THE API. +## http://www.pubnub.com/account +## +## ---------------------------------------------------- + +## -------------------------------------------------- +## PubNub 3.3 Web Data Push Cloud-hosted API - PYTHON +## -------------------------------------------------- +## +## www.pubnub.com - PubNub Web Data Push Service in the Cloud.  +## http://github.com/pubnub/pubnub-api/tree/master/python +## +## PubNub is a Massively Scalable Data Push Service for Web and Mobile Games. +## This is a cloud-based service for broadcasting messages +## to thousands of web and mobile clients simultaneously. + +## --------------- +## Python Push API +## --------------- + +### Check out additional tests and examples in the 3.2 directory! + +pubnub = Pubnub( +    "demo",  ## PUBLISH_KEY +    "demo",  ## SUBSCRIBE_KEY +    None,    ## SECRET_KEY +    False    ## SSL_ON? +) + +# ------- +# PUBLISH +# ------- +# Send Message +info = pubnub.publish({ +    'channel' : 'hello_world', +    'message' : { +        'some_text' : 'Hello my World' +    } +}) +print(info) + +# --------- +# SUBSCRIBE +# --------- +# Listen for Messages *BLOCKING* +def receive(message) : +    print(message) +    return True + +pubnub.subscribe({ +    'channel'  : 'hello_world', +    'callback' : receive  +}) + +# --------- +# PRESENCE +# --------- +# Listen for Presence Event Messages *BLOCKING* + +def pres_event(message) : +    print(message) +    return True + +pubnub.presence({ +    'channel'  : 'hello_world', +    'callback' : receive  +}) + +# --------- +# HERE_NOW +# --------- +# Get info on who is here right now! + +here_now = pubnub.here_now({ +    'channel' : 'hello_world', +}) + +print(here_now['occupancy']) +print(here_now['uuids']) + + +# ------------------ +## Channel Analytics +# ------------------ +analytics = pubnub.analytics({ +    'channel'  : 'channel-name-here', ## Leave blank for all channels +    'limit'    : 100,                 ## aggregation range +    'ago'      : 0,                   ## minutes ago to look backward +    'duration' : 100                  ## minutes offset +}) +print(analytics) + +# ------- +# HISTORY +# ------- +# Load Previously Published Messages +history = pubnub.history({ +    'channel' : 'hello_world', +    'limit'   : 1 +}) +print(history) + + +# ------- +# DETAILED HISTORY +# ------- +# Load Previously Published Messages in Detail +	@param array args with 'channel', optional: 'start', 'end', 'reverse', 'count' +	'channel'-Channel name +	'start'-Start timestamp +	'end'-End timestamp +	'reverse'-Order of History +	'count'-Number of History messages +	 + 	NSInteger count = 3; +    NSNumber * aCountInt = [NSNumber numberWithInteger:count]; +    [pubnub detailedHistory:[NSDictionary dictionaryWithObjectsAndKeys: +                             aCountInt,@"count", +                             @"hello_world",@"channel", +                             nil]]; + | 
