diff options
| author | Devendra | 2014-06-18 01:02:15 +0530 | 
|---|---|---|
| committer | Devendra | 2014-06-18 01:02:15 +0530 | 
| commit | a1ee7f8bd90b463318bfa75f7ee4f58d458d2a24 (patch) | |
| tree | 9e260902f960f792a93fa25e3b619c42ecb5f4d4 /python | |
| parent | bfd5c64bdf7ed45f21207cb53c653e7220e39eff (diff) | |
| parent | 083127cde127dd78fc88ffe2b3b82144b2c07038 (diff) | |
| download | pubnub-python-a1ee7f8bd90b463318bfa75f7ee4f58d458d2a24.tar.bz2 | |
Merge branch 'master' into develop
Diffstat (limited to 'python')
28 files changed, 3173 insertions, 1073 deletions
| diff --git a/python/Makefile b/python/Makefile deleted file mode 100644 index 5eb9e2f..0000000 --- a/python/Makefile +++ /dev/null @@ -1,29 +0,0 @@ -include ../Makefile.inc - - -.PHONY: all -all: build - -.PHONY: build -build: -	cat ../common/LICENSE_HEADER > ./Pubnub.py -	echo "\n" >> ./Pubnub.py -	cat ../common/PubnubCrypto.py >> ./Pubnub.py -	echo "\n" >> ./Pubnub.py -	cat ../common/PubnubBase.py >> ./Pubnub.py -	echo "\n" >> ./Pubnub.py -	cat ../common/PubnubCore.py >> ./Pubnub.py -	echo "\n" >> ./Pubnub.py -	cat ./unassembled/Platform.py >> ./Pubnub.py -	find -name "Pubnub*py" | xargs sed -i "s/PubNub\ [0-9]\.[0-9]\.[0-9]/PubNub\ $(VERSION)/g" - - -.PHONY: clean -clean: -	rm -f Pubnub.py* - -.PHONY: test -test: -	python tests/detailed-history-unit-test.py -	python tests/unit-test.py - diff --git a/python/Pubnub.py b/python/Pubnub.py deleted file mode 100644 index 59a38af..0000000 --- a/python/Pubnub.py +++ /dev/null @@ -1,618 +0,0 @@ -## www.pubnub.com - PubNub Real-time push service in the cloud.  -# coding=utf8 - -## PubNub Real-time Push APIs and Notifications Framework -## Copyright (c) 2010 Stephen Blum -## http://www.pubnub.com/ - -## ----------------------------------- -## PubNub 3.3.5 Real-time Push Cloud API -## ----------------------------------- - - -from Crypto.Cipher import AES -from Crypto.Hash import MD5 -from base64 import encodestring, decodestring  -import hashlib -import hmac - -class 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. -        #** -        """ -        padding = block_size - (len(msg) % block_size) -        return msg + chr(padding)*padding -        -    def depad( self, msg ): -        """ -        #** -        #* depad -        #* -        #* depad the decryptet message" -        #* @return msg without padding. -        #** -        """ -        return msg[0:-ord(msg[-1])] - -    def getSecret( self, key ): -        """ -        #** -        #* getSecret -        #* -        #* hases the key to MD5 -        #* @return key in MD5 format -        #** -        """ -        return hashlib.sha256(key).hexdigest() - -    def encrypt( self, key, msg ): -        """ -        #** -        #* encrypt -        #* -        #* encrypts the message -        #* @return message in encrypted format -        #** -        """ -        secret = self.getSecret(key) -        Initial16bytes='0123456789012345' -        cipher = AES.new(secret[0:32],AES.MODE_CBC,Initial16bytes) -        enc = encodestring(cipher.encrypt(self.pad(msg))) -        return enc -    def decrypt( self, key, msg ): -        """ -        #** -        #* decrypt -        #* -        #* decrypts the message -        #* @return message in decryped format -        #** -        """ -        secret = self.getSecret(key) -        Initial16bytes='0123456789012345' -        cipher = AES.new(secret[0:32],AES.MODE_CBC,Initial16bytes) -        return self.depad((cipher.decrypt(decodestring(msg)))) - - -try: import json -except ImportError: import simplejson as json - -import time -import hashlib -import urllib2 -import uuid  - -class PubnubBase(object): -    def __init__( -        self, -        publish_key, -        subscribe_key, -        secret_key = False, -        cipher_key = False, -        ssl_on = False, -        origin = 'pubsub.pubnub.com', -        UUID = None -    ) : -        """ -        #** -        #* Pubnub -        #* -        #* Init the Pubnub Client API -        #* -        #* @param string publish_key required key to send messages. -        #* @param string subscribe_key required key to receive messages. -        #* @param string secret_key optional key to sign messages. -        #* @param boolean ssl required for 2048 bit encrypted messages. -        #* @param string origin PUBNUB Server Origin. -        #* @param string pres_uuid optional identifier for presence (auto-generated if not supplied) -        #** - -        ## Initiat Class -        pubnub = Pubnub( 'PUBLISH-KEY', 'SUBSCRIBE-KEY', 'SECRET-KEY', False ) - -        """ -        self.origin        = origin -        self.limit         = 1800 -        self.publish_key   = publish_key -        self.subscribe_key = subscribe_key -        self.secret_key    = secret_key -        self.cipher_key    = cipher_key -        self.ssl           = ssl_on -        self.pc            = PubnubCrypto() - -        if self.ssl : -            self.origin = 'https://' + self.origin -        else : -            self.origin = 'http://'  + self.origin -         -        self.uuid = UUID or str(uuid.uuid4()) -         -        if not isinstance(self.uuid, basestring): -            raise AttributeError("pres_uuid must be a string") - -    def sign(self, channel, message): -        ## Sign Message -        if self.secret_key: -            signature = hashlib.md5('/'.join([ -                self.publish_key, -                self.subscribe_key, -                self.secret_key, -                channel, -                message -            ])).hexdigest() -        else: -            signature = '0' -        return signature - -    def encrypt(self, message): -        if self.cipher_key: -            message = json.dumps(self.pc.encrypt(self.cipher_key, json.dumps(message)).replace('\n','')) -        else : -            message = json.dumps(message) - -        return message; - -    def decrypt(self, message): -        if self.cipher_key: -            message = self.pc.decrypt(self.cipher_key, message) - -        return message - - -    def 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']) - -        ## Capture Callback -        if args.has_key('callback') : -            callback = args['callback'] -        else : -            callback = None  - -        #message = json.dumps(args['message'], separators=(',',':')) -        message = self.encrypt(args['message']) - -        signature = self.sign(channel, message) - -        ## Send Message -        return self._request({"urlcomponents": [ -            'publish', -            self.publish_key, -            self.subscribe_key, -            signature, -            channel, -            '0', -            message -        ]}, callback) -     -    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']) - -        ## Capture Callback -        if args.has_key('callback') : -            callback = args['callback'] -        else : -            callback = None -         -        ## Fail if bad input. -        if not channel : -            raise Exception('Missing Channel') -            return False -         -        ## Get Presence Here Now -        return self._request({"urlcomponents": [ -            'v2','presence', -            'sub_key', self.subscribe_key, -            'channel', channel -        ]}, callback); -         -         -    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 - -        ## Capture Callback -        if args.has_key('callback') : -            callback = args['callback'] -        else : -            callback = None - -        ## Get History -        return self._request({ "urlcomponents" : [ -            'history', -            self.subscribe_key, -            channel, -            '0', -            str(limit) -        ] }, callback); - -    def detailedHistory(self, args) : -        """ -        #** -        #* Detailed History -        #* -        #* Load Detailed history from a channel. -        #* -        #* @param array args with 'channel', optional: 'start', 'end', 'reverse', 'count' -        #* @return mixed false on fail, array on success. -        #* - -        ## History Example -        history = pubnub.detailedHistory({ -            'channel' : 'hello_world', -            'count'   : 5 -        }) -        print(history) - -        """ -        ## Capture User Input -        channel = str(args['channel']) - -        params = dict()  -        count = 100     -         -        if args.has_key('count'): -            count = int(args['count']) - -        params['count'] = str(count)     -         -        if args.has_key('reverse'): -            params['reverse'] = str(args['reverse']).lower() - -        if args.has_key('start'): -            params['start'] = str(args['start']) - -        if args.has_key('end'): -            params['end'] = str(args['end']) - -        ## Fail if bad input. -        if not channel : -            raise Exception('Missing Channel') -            return False - -        ## Capture Callback -        if args.has_key('callback') : -            callback = args['callback'] -        else : -            callback = None  - -        ## Get History -        return self._request({ 'urlcomponents' : [ -            'v2', -            'history', -            'sub-key', -            self.subscribe_key, -            'channel', -            channel, -        ],'urlparams' : params }, callback=callback); - -    def time(self, args = None) : -        """ -        #** -        #* Time -        #* -        #* Timestamp from PubNub Cloud. -        #* -        #* @return int timestamp. -        #* - -        ## PubNub Server Time Example -        timestamp = pubnub.time() -        print(timestamp) - -        """ -        ## Capture Callback -        if args and args.has_key('callback') : -            callback = args['callback'] -        else : -            callback = None  -        time = self._request({'urlcomponents' : [ -            'time', -            '0' -        ]}, callback) -        if time != None: -            return time[0] - - -    def _encode( self, request ) : -        return [ -            "".join([ ' ~`!@#$%^&*()+=[]\\{}|;\':",./<>?'.find(ch) > -1 and -                hex(ord(ch)).replace( '0x', '%' ).upper() or -                ch for ch in list(bit) -            ]) for bit in request] -     -    def getUrl(self,request): -        ## Build URL -        url = self.origin + '/' + "/".join([ -            "".join([ ' ~`!@#$%^&*()+=[]\\{}|;\':",./<>?'.find(ch) > -1 and -                hex(ord(ch)).replace( '0x', '%' ).upper() or -                ch for ch in list(bit) -            ]) for bit in request["urlcomponents"]]) -        if (request.has_key("urlparams")): -            url = url + '?' + "&".join([ x + "=" + y  for x,y in request["urlparams"].iteritems()]) -        return url - - -class PubnubCore(PubnubBase): -    def __init__( -        self, -        publish_key, -        subscribe_key, -        secret_key = False, -        cipher_key = False, -        ssl_on = False, -        origin = 'pubsub.pubnub.com', -        uuid = None -    ) : -        """ -        #** -        #* Pubnub -        #* -        #* Init the Pubnub Client API -        #* -        #* @param string publish_key required key to send messages. -        #* @param string subscribe_key required key to receive messages. -        #* @param string secret_key optional key to sign messages. -        #* @param boolean ssl required for 2048 bit encrypted messages. -        #* @param string origin PUBNUB Server Origin. -        #* @param string pres_uuid optional identifier for presence (auto-generated if not supplied) -        #** - -        ## Initiat Class -        pubnub = Pubnub( 'PUBLISH-KEY', 'SUBSCRIBE-KEY', 'SECRET-KEY', False ) - -        """ -        super(PubnubCore, self).__init__( -            publish_key=publish_key, -            subscribe_key=subscribe_key, -            secret_key=secret_key, -            cipher_key=cipher_key, -            ssl_on=ssl_on, -            origin=origin, -            UUID=uuid -        )         - -        self.subscriptions = {} -        self.timetoken     = 0 -        self.version       = '3.4' -        self.accept_encoding = 'gzip' - - - -    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({"urlcomponents" : [ -                    'subscribe', -                    subscribe_key, -                    channel, -                    '0', -                    str(timetoken) -                ],"urlparams" : {"uuid" : self.uuid }}) - -                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(self.decrypt(message)) : -                        return - -            except Exception: -                time.sleep(1) - -        return True - - - -class Pubnub(PubnubCore): -    def __init__( -        self, -        publish_key, -        subscribe_key, -        secret_key = False, -        cipher_key = False, -        ssl_on = False, -        origin = 'pubsub.pubnub.com', -        pres_uuid = None -    ) : -        super(Pubnub, self).__init__( -            publish_key = publish_key, -            subscribe_key = subscribe_key, -            secret_key = secret_key, -            cipher_key = cipher_key, -            ssl_on = ssl_on, -            origin = origin, -            uuid = pres_uuid -        )         - -    def _request( self, request, callback = None ) : -        ## Build URL -        url = self.getUrl(request) - -        ## Send Request Expecting JSONP Response -        try: -            try: usock = urllib2.urlopen( url, None, 310 ) -            except TypeError: usock = urllib2.urlopen( url, None ) -            response = usock.read() -            usock.close() -            resp_json = json.loads(response) -        except: -            return None -             -        if (callback): -            callback(resp_json) -        else: -            return resp_json diff --git a/python/README.md b/python/README.md index 68065f0..c077918 100644 --- a/python/README.md +++ b/python/README.md @@ -1,60 +1,93 @@ -## 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/python +## Contact support@pubnub.com for all questions +#### [PubNub](http://www.pubnub.com) Real-time Data Network +##### Standalone Python Client  #### Init  ``` -pubnub = Pubnub( -    "demo",  ## PUBLISH_KEY -    "demo",  ## SUBSCRIBE_KEY -    None,    ## SECRET_KEY -    False    ## SSL_ON? -) +pubnub = Pubnub(publish_key="demo", subscribe_key="demo", ssl_on=False) +  ```  #### PUBLISH  ``` -info = pubnub.publish({ -    'channel' : 'hello_world', -    'message' : { -        'some_text' : 'Hello my World' -    } -}) -print(info) +channel = 'hello_world' +message = 'Hello World !!!' + +# Synchronous usage +print pubnub.publish(channel='hello_world', message='Hello World !!!') + +# Asynchronous usage + +def callback(message): +    print(message) + +pubnub.publish(channel, message, callback=callback, error=callback) +  ```  #### SUBSCRIBE  ``` -# Listen for Messages *BLOCKING* -def receive(message) : +# Listen for Messages + +channel = 'hello_world' + +def callback(message, channel):      print(message) -    return True -pubnub.subscribe({ -    'channel'  : 'hello_world', -    'callback' : receive  -}) + +def error(message): +    print("ERROR : " + str(message)) + + +def connect(message): +    print("CONNECTED") + + +def reconnect(message): +    print("RECONNECTED") + + +def disconnect(message): +    print("DISCONNECTED") + + +pubnub.subscribe(channel, callback=callback, error=callback, +                 connect=connect, reconnect=reconnect, disconnect=disconnect) +``` + +#### UNSUBSCRIBE + +``` +# Listen for Messages + +channel = 'hello_world' + +pubnub.unsubscribe(channel=channel)  ```  #### PRESENCE  ``` -# Listen for Presence Event Messages *BLOCKING* +# Listen for Presence Event Messages + +channel = 'hello_world' -def pres_event(message) : +def callback(message, channel):      print(message) -    return True -pubnub.presence({ -    'channel'  : 'hello_world', -    'callback' : receive  -}) + +def error(message): +    print("ERROR : " + str(message)) + + + +pubnub.presence(channel, callback=callback, error=callback)  ```  #### HERE_NOW @@ -62,36 +95,33 @@ pubnub.presence({  ```  # Get info on who is here right now! -here_now = pubnub.here_now({ -    'channel' : 'hello_world', -}) +channel = 'hello_world' -print(here_now['occupancy']) -print(here_now['uuids']) -``` +# Synchronous usage +print pubnub.here_now(channel) -#### 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) +# Asynchronous usage + +def callback(message): +    print(message) +pubnub.here_now(channel, callback=callback, error=callback)  ```  #### HISTORY  ``` -# Load Previously Published Messages -history = pubnub.detailedHistory({ -    'channel'   : 'my_channel', -    'end'       : my_end_time_token, # Optional -    'start'     : my_start_time_token, # Optional -    'count'     : num_of_msgs_to_return # Optional, default is 100 -}) -print(history) +# Synchronous usage + +print pubnub.history(channel, count=2) + +# Asynchronous usage + + +def callback(message): +    print(message) + +pubnub.history(channel, count=2, callback=callback, error=callback)  ``` +## Contact support@pubnub.com for all questions diff --git a/python/examples/config b/python/examples/config new file mode 100644 index 0000000..f35134f --- /dev/null +++ b/python/examples/config @@ -0,0 +1,9 @@ +sessionname pubnub-console +screen -t output tail -f ./pubnub-console.log +split +focus down +screen -t console  python console.py "set_output_file" +split -v +focus down +screen -t help vi -R ./console-help.txt +focus up diff --git a/python/examples/config_osx b/python/examples/config_osx new file mode 100644 index 0000000..cdb186c --- /dev/null +++ b/python/examples/config_osx @@ -0,0 +1,8 @@ +sessionname pubnub-console +screen -t help vi -R ./console-help.txt +split +focus down +screen -t output tail -f ./pubnub-console.log +split  +focus down +screen -t console  python console.py "set_output_file" diff --git a/python/examples/console-help.txt b/python/examples/console-help.txt new file mode 100644 index 0000000..abe92c8 --- /dev/null +++ b/python/examples/console-help.txt @@ -0,0 +1,37 @@ +********************** HELP ****************************** + +TO EXIT :    +Ctrl-A \  followed by y ( on linux ) +Ctrl-A Ctrl-\ followed by y ( on mac osx ) + +TO MOVE BETWEEN PANES  . Ctrl-A  TAB + +********************************************************** + +PUBLISH + +Usage: publish [options] arg + +Options: +  -h, --help            show this help message and exit +  -c CHANNEL, --channel=CHANNEL +                        Channel on which to publish + +Examples: +   (1)  publish -c hello_world  hi how r u +   (2)  pub -c hello_world  [1,2] + + + +SUBSCRIBE + +Usage: subscribe [options] arg + +Options: +  -h, --help            show this help message and exit +  -c CHANNEL, --channel=CHANNEL +                        Channel for subscribe + +Examples: +   (1)  subscribe -c hello_world +   (2)  sub -c hello_world
\ No newline at end of file diff --git a/python/examples/console.py b/python/examples/console.py new file mode 100644 index 0000000..bf82b5f --- /dev/null +++ b/python/examples/console.py @@ -0,0 +1,689 @@ +## 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/ + + +import sys +from Pubnub import Pubnub +import threading +from datetime import datetime + +from cmd2 import Cmd, make_option, options, Cmd2TestCase +import optparse +import json + +import atexit +import os +import readline +import rlcompleter + +import pygments +from pygments.lexers import JsonLexer +from pygments.formatters import TerminalFormatter + +lexer = JsonLexer() +formatter = TerminalFormatter() +def highlight(msg): +    return pygments.highlight(msg, lexer, formatter) + + + +historyPath = os.path.expanduser("~/.pubnub_console_history") + + +def save_history(historyPath=historyPath): +    import readline +    readline.write_history_file(historyPath) + +if os.path.exists(historyPath): +    readline.read_history_file(historyPath) + +atexit.register(save_history) + +of = sys.stdout + +color = Cmd() + +stop = None + +full_date = False + + +def stop_2(th): +    th._Thread__stop() + + +def stop_3(th): +    th._stop() + + +def print_console_2(of, message): +    print >>of, message + + +def print_console_3(of, message): +    of.write(message) +    of.write("\n") + +print_console = None + +if type(sys.version_info) is tuple: +    print_console = print_console_2 +    stop = stop_2 +else: +    if sys.version_info.major == 2: +        print_console = print_console_2 +        stop = stop_2 +    else: +        print_console = print_console_3 +        stop = stop_3 + + +def get_date(): +    if full_date is True: +        return color.colorize(datetime.now().strftime( +            '%Y-%m-%d %H:%M:%S'), "magenta") +    else: +        return color.colorize(datetime.now().strftime( +            '%H:%M:%S'), "magenta") + +def print_ok_normal(msg, channel=None): +    if msg is None: +        return +    chstr = color.colorize("[" + get_date() + "] ", "magenta") +    chstr += color.colorize("[Channel : " + channel + +                            "] " if channel is not None else "", "cyan") +    try: +        print_console(of, (chstr + color.colorize(str(msg), "green"))) +    except UnicodeEncodeError as e: +        print_console(of, (msg)) + +    of.flush() + + +def print_error_normal(msg, channel=None): +    if msg is None: +        return +    chstr = color.colorize("[" + get_date() + "] ", "magenta") +    chstr += color.colorize("[Channel : " + channel + +                            "] " if channel is not None else "", "cyan") +    try: +        print_console(of, (chstr + color.colorize(color.colorize( +            str(msg), "red"), "bold"))) +    except UnicodeEncodeError as e: +        print_console(of, (msg)) +    of.flush() + +def print_ok_pretty(msg, channel=None): +    if msg is None: +        return +    chstr = color.colorize("[" + get_date() + "] ", "magenta") +    chstr += color.colorize("[Channel : " + channel + +                            "] " if channel is not None else "", "cyan") +    try: +        print_console(of, (chstr + highlight(json.dumps(msg, indent=2)))) +    except UnicodeEncodeError as e: +        print_console(of, (msg)) + +    of.flush() + + +def print_error_pretty(msg, channel=None): +    if msg is None: +        return +    chstr = color.colorize("[" + get_date() + "] ", "magenta") +    chstr += color.colorize("[Channel : " + channel + +                            "] " if channel is not None else "", "cyan") +    try: +        print_console(of, (chstr + color.colorize(color.colorize( +            "ERROR: ", "red"), "bold") + +            highlight(json.dumps(msg, indent=2)))) +    except UnicodeEncodeError as e: +        print_console(of, (msg)) +    of.flush() + +print_ok = print_ok_pretty +print_error = print_error_pretty + + +class DefaultPubnub(object): +    def handlerFunctionClosure(self, name): +        def handlerFunction(*args, **kwargs): +            print_error("Pubnub not initialized." + +                        "Use init command to initialize") +        return handlerFunction + +    def __getattr__(self, name): +        return self.handlerFunctionClosure(name) + +pubnub = DefaultPubnub() + + +def kill_all_threads(): +    for thread in threading.enumerate(): +        if thread.isAlive(): +            stop(thread) + + +def get_input(message, t=None): +    while True: +        try: +            try: +                command = raw_input(message) +            except NameError: +                command = input(message) +            except KeyboardInterrupt: +                return None + +            command = command.strip() + +            if command is None or len(command) == 0: +                raise ValueError + +            if t is not None and t == bool: +                valid = ["True", "true", "1", 1, "y", "Y", "yes", "Yes", "YES"] +                if command in valid: +                    return True +                else: +                    return False +            if t is not None: +                command = t(command) +            else: +                command = eval("'" + command + "'") + +            return command +        except ValueError: +            print_error("Invalid input : " + command) + + +def _publish_command_handler(channel, message, async=False): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) +    print_ok(pubnub.publish(channel, message, +                            _callback if async is True else None, +                            _error if async is True else None)) + + +def _subscribe_command_handler(channel): + +    def _callback(r, ch): +        print_ok(r, ch) + +    def _error(r, ch=None): +        print_error(r, ch if ch is not None else channel) + +    def _disconnect(r): +        print_error("DISCONNECTED", r) + +    def _reconnect(r): +        print_error("RECONNECTED", r) + +    def _connect(r): +        print_error("CONNECTED", r) + +    pubnub.subscribe(channel, _callback, _error, connect=_connect, +                     disconnect=_disconnect, reconnect=_reconnect) + + +def _unsubscribe_command_handler(channels): + +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) +    if not isinstance(channels, list): +        ch = [] +        ch.append(channels) +        channels = ch + +    for channel in channels: +        pubnub.unsubscribe(channel) +        pubnub.unsubscribe(channel + '-pnpres') +    print_ok('Unsubscribed from : ' + str(channels)) + + +def _grant_command_handler(channel, auth_key, read, write, ttl, async=False): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) + +    print_ok(pubnub.grant(channel, auth_key, +                          read, write, ttl, +                          _callback if async is True else None, +                          _error if async is True else None)) + + +def _revoke_command_handler(channel, auth_key, ttl, async=False): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) + +    print_ok(pubnub.revoke(channel, auth_key, ttl, +                           _callback if async is True else None, +                           _error if async is True else None)) + + +def _audit_command_handler(channel, auth_key, async=False): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) + +    print_ok(pubnub.audit(channel, auth_key, +                          _callback if async is True else None, +                          _error if async is True else None)) + + +def _history_command_handler(channel, count, async=False): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) + +    print_ok(pubnub.history(channel, count, +                            _callback if async is True else None, +                            _error if async is True else None)) + + +def _here_now_command_handler(channel, async=False): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) + +    print_ok(pubnub.here_now(channel, _callback if async is True else None, +                             _error if async is True else None)) + + +def kill_all_threads(): +    for thread in threading.enumerate(): +        if thread.isAlive(): +            stop(thread) + + +def get_channel_array(): +    channels = pubnub.get_channel_array() + +    for channel in channels: +        if "-pnpres" in channel: +            i = channels.index(channel.split("-pnpres")[0]) +            channels[i] = channels[i] + color.colorize("(P)", "blue") +            channels.remove(channel) +    return channels + + +class DevConsole(Cmd): +    def __init__(self): +        Cmd.__init__(self) +        global pubnub +        self.intro = "For Help type ? or help . " + \ +            "To quit/exit type exit" +        self.default_channel = None +        self.async = False +        pubnub = Pubnub("demo", "demo") +        self.channel_truncation = 3 +        self.prompt = self.get_prompt() +        self.publish_key = "demo" +        self.subscribe_key = "demo" +        self.origin = "pubsub.pubnub.com" +        self.auth_key = None +        self.cipher_key = None +        self.secret_key = "demo" +        self.ssl = False +        self.uuid = None +        self.disable_pretty = False + +    def get_channel_origin(self): +        cho = " [" +        channels = get_channel_array() +        channels_str = ",".join(channels) +        sl = self.channel_truncation +        if len(channels) > int(sl) and int(sl) > 0: +            cho += ",".join(channels[:int(sl)]) + " " + str( +                len(channels) - int(sl)) + " more..." +        else: +            cho += ",".join(channels) + +        if len(channels) > 0: +            cho = color.colorize(cho, "bold") + "@" + +        origin = pubnub.get_origin().split("://")[1] +        origin += color.colorize(" (SSL)", "green") if pubnub.get_origin( +        ).split("://")[0] == "https" else "" +        return cho + color.colorize(origin, "blue") + "] > " + +    def get_prompt(self): +        prompt = "[" + get_date() + "]" + +        if self.default_channel is not None and len(self.default_channel) > 0: +            prompt += " [default channel: " + color.colorize( +                self.default_channel, "bold") + "]" + +        prompt += self.get_channel_origin() +        return prompt + +    def precmd(self, line): +        self.prompt = self.get_prompt() +        return line + +    #def emptyline(self): +    #    self.prompt = self.get_prompt() + +    def cmdloop_with_keyboard_interrupt(self): +        try: +            self.cmdloop() +        except KeyboardInterrupt as e: +            pass +        sys.stdout.write('\n') +        kill_all_threads() + +    @options([make_option('-p', '--publish-key', action="store", +                          default=None, help="Publish Key"), +              make_option('-s', '--subscribe-key', action="store", +                          default=None, help="Subscribe Key"), +              make_option('-k', '--secret-key', action="store", +                          default=None, help="cipher Key"), +              make_option('-c', '--cipher-key', action="store", +                          default=None, help="Secret Key"), +              make_option('-a', '--auth-key', action="store", +                          default=None, help="Auth Key"), +              make_option('--ssl-on', dest='ssl', action='store_true', +                          default=False, help="SSL Enabled ?"), +              make_option('-o', '--origin', action="store", +                          default=None, help="Origin"), +              make_option('-u', '--uuid', action="store", +                          default=None, help="UUID"), +              make_option('--disable-pretty-print', dest='disable_pretty', action='store_true', +                          default=False, help="Disable Pretty Print ?") +              ]) +    def do_init(self, command, opts): +        global pubnub +        global print_ok +        global print_error +        global print_ok_normal +        global print_error_normal +        global print_error_pretty +        global print_ok_pretty + +        self.publish_key = opts.publish_key if opts.publish_key is not None else self.publish_key +        self.subscribe_key = opts.subscribe_key if opts.subscribe_key is not None else self.subscribe_key +        self.secret_key = opts.secret_key if opts.secret_key is not None else self.secret_key +        self.cipher_key = opts.cipher_key if opts.cipher_key is not None else self.cipher_key +        self.auth_key = opts.auth_key if opts.auth_key is not None else self.auth_key +        self.origin = opts.origin if opts.origin is not None else self.origin +        self.uuid = opts.uuid if opts.uuid is not None else self.uuid +        self.ssl = opts.ssl if opts.ssl is not None else self.ssl +        self.disable_pretty = opts.disable_pretty if opts.disable_pretty is not None else self.disable_pretty + +        pubnub = Pubnub(self.publish_key, +                        self.subscribe_key, +                        self.secret_key, +                        self.cipher_key, +                        self.auth_key, +                        self.ssl, +                        self.origin, +                        self.uuid) +        self.prompt = self.get_prompt() + +        if opts.disable_pretty is True: +            print_ok = print_ok_normal +            print_error = print_error_normal +        else: +            print_ok = print_ok_pretty +            print_error = print_error_pretty + +    def do_set_sync(self, command): +        """unset_async +        Unset Async mode""" +        self.async = False + +    def do_set_async(self, command): +        """set_async +        Set Async mode""" +        self.async = True + +    @options([make_option('-n', '--count', action="store", +                          default=3, help="Number of channels on prompt") +              ]) +    def do_set_channel_truncation(self, command, opts): +        """set_channel_truncation +        Set Channel Truncation""" + +        self.channel_truncation = opts.count + +        self.prompt = self.get_prompt() + +    def do_unset_channel_truncation(self, command): +        """unset_channel_truncation +        Unset Channel Truncation""" +        self.channel_truncation = 0 +        self.prompt = self.get_prompt() + +    def do_set_full_date(self, command): +        global full_date +        """do_set_full_date +        Set Full Date""" +        full_date = True +        self.prompt = self.get_prompt() + +    def do_unset_full_date(self, command): +        global full_date +        """do_unset_full_date +        Unset Full Date""" +        full_date = False +        self.prompt = self.get_prompt() + +    @options([make_option('-c', '--channel', +                          action="store", help="Default Channel") +              ]) +    def do_set_default_channel(self, command, opts): + +        if opts.channel is None: +            print_error("Missing channel") +            return +        self.default_channel = opts.channel +        self.prompt = self.get_prompt() + +    @options([make_option('-f', '--file', action="store", +                          default="./pubnub-console.log", help="Output file") +              ]) +    def do_set_output_file(self, command, opts): +        global of +        try: +            of = file(opts.file, 'w+') +        except IOError as e: +            print_error("Could not set output file. " + e.reason) + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel for here now data") +              ]) +    def do_here_now(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel +        if opts.channel is None: +            print_error("Missing channel") +            return + +        _here_now_command_handler(opts.channel, async=self.async) + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel for history data"), +              make_option('-n', '--count', action="store", +                          default=5, help="Number of messages") +              ]) +    def do_get_history(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel +        if opts.channel is None: +            print_error("Missing channel") +            return + +        _history_command_handler(opts.channel, opts.count, async=self.async) + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel on which to publish") +              ]) +    def do_publish(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel +        if opts.channel is None: +            print_error("Missing channel") +            return + +        if command is None: +            print_error("Missing message") +            return + +        try: +            message = json.loads(str(command)) +        except ValueError as ve: +            message = str(command) + +        _publish_command_handler(opts.channel, message, async=self.async) + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel on which to grant"), +              make_option('-a', '--auth-key', dest="auth_key", +                          action="store", +                          help="Auth Key"), +              make_option('-r', '--read-enabled', dest='read', +                          action='store_true', +                          default=False, help="Read ?"), +              make_option('-w', '--write-enabled', dest='write', +                          action='store_true', +                          default=False, help="Write ?"), +              make_option('-t', '--ttl', action="store", +                          default=5, help="TTL"), +              make_option('-p', '--presence', action="store_true", +                          dest="presence", +                          default=False, help="Grant on presence channel ?") +              ]) +    def do_grant(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel + +        opts.auth_key = pubnub.auth_key \ +            if opts.auth_key is None else opts.auth_key + +        _grant_command_handler(opts.channel, opts.auth_key, +                               opts.read, opts.write, +                               opts.ttl, async=self.async) + +        if opts.presence is True: +            _grant_command_handler(opts.channel + '-pnpres', opts.auth_key, +                                   opts.read, opts.write, +                                   opts.ttl, async=self.async) + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel on which to revoke"), +              make_option('-a', '--auth-key', dest="auth_key", action="store", +                          help="Auth Key"), +              make_option('-t', '--ttl', action="store", +                          default=5, help="TTL"), +              make_option('-p', '--presence', action="store_true", +                          dest="presence", +                          default=False, help="Revoke on presence channel ?") +              ]) +    def do_revoke(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel + +        opts.auth_key = pubnub.auth_key \ +            if opts.auth_key is None else opts.auth_key + +        _revoke_command_handler( +            opts.channel, opts.auth_key, opts.ttl, async=self.async) + +        if opts.presence is True: +            _revoke_command_handler( +                opts.channel + '-pnpres', opts.auth_key, +                opts.ttl, async=self.async) + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel on which to revoke"), +              make_option('-a', '--auth-key', dest="auth_key", action="store", +                          help="Auth Key") +              ]) +    def do_audit(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel + +        opts.auth_key = pubnub.auth_key \ +            if opts.auth_key is None else opts.auth_key + +        _audit_command_handler(opts.channel, opts.auth_key, async=self.async) + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel for unsubscribe"), +              make_option('-a', '--all', action="store_true", dest="all", +                          default=False, help="Unsubscribe from all channels") +              ]) +    def do_unsubscribe(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel +        if (opts.all is True): +            opts.channel = pubnub.get_channel_array() +        if opts.channel is None: +            print_error("Missing channel") +            return +        _unsubscribe_command_handler(opts.channel) +        self.prompt = self.get_prompt() + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel for subscribe"), +              make_option('-g', '--get-channel-list', action="store_true", +                          dest="get", +                          default=False, help="Get susbcribed channel list"), +              make_option('-p', '--presence', action="store_true", +                          dest="presence", +                          default=False, help="Presence events ?") +              ]) +    def do_subscribe(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel +        if opts is None: +            print_error("Missing argument") +            return + +        if opts.channel is not None: +            _subscribe_command_handler(opts.channel) + +        if opts.presence is True: +            _subscribe_command_handler(opts.channel + '-pnpres') + +        if opts.get is True: +            print_ok(get_channel_array()) +        self.prompt = self.get_prompt() + +    def do_exit(self, args): +        kill_all_threads() +        return -1 + +    #def do_EOF(self, args): +    #    kill_all_threads() +    #    return self.do_exit(args) + +    #def handler(self, signum, frame): +    #    kill_all_threads() + + +def main(): +    app = DevConsole() +    app.cmdloop_with_keyboard_interrupt() + +if __name__ == "__main__": +    main() diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py new file mode 100755 index 0000000..134d2e7 --- /dev/null +++ b/python/examples/dev-console.py @@ -0,0 +1,278 @@ +## 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/ + +import sys +from Pubnub import Pubnub + +from optparse import OptionParser + + +parser = OptionParser() + +parser.add_option("--publish-key", +                  dest="publish_key", default="demo", +                  help="Publish Key ( default : 'demo' )") + +parser.add_option("--subscribe-key", +                  dest="subscribe_key", default="demo", +                  help="Subscribe Key ( default : 'demo' )") + +parser.add_option("--secret-key", +                  dest="secret_key", default="demo", +                  help="Secret Key ( default : 'demo' )") + +parser.add_option("--cipher-key", +                  dest="cipher_key", default="", +                  help="Cipher Key") + +parser.add_option("--auth-key", +                  dest="auth_key", default=None, +                  help="Auth Key") + +parser.add_option("--origin", +                  dest="origin", default="pubsub.pubnub.com", +                  help="Origin ( default: pubsub.pubnub.com )") + +parser.add_option("--ssl-on", +                  action="store_false", dest="ssl", default=False, +                  help="SSL") + +parser.add_option("--uuid", +                  dest="uuid", default=None, +                  help="UUID") + +(options, args) = parser.parse_args() + +print(options) + +pubnub = Pubnub(options.publish_key, +                options.subscribe_key, +                options.secret_key, +                options.cipher_key, +                options.auth_key, +                options.ssl, +                options.origin, +                options.uuid) + + +class color(object): +    PURPLE = '\033[95m' +    CYAN = '\033[96m' +    DARKCYAN = '\033[36m' +    BLUE = '\033[94m' +    GREEN = '\033[92m' +    YELLOW = '\033[93m' +    RED = '\033[91m' +    BOLD = '\033[1m' +    UNDERLINE = '\033[4m' +    END = '\033[0m' + +from datetime import datetime + + +def print_ok(msg, channel=None): +    chstr = color.PURPLE + "[" + datetime.now().strftime( +        '%Y-%m-%d %H:%M:%S') + "] " + color.END +    chstr += color.CYAN + "[Channel : " + channel + \ +        "] " if channel is not None else "" + color.END +    try: +        print(chstr + color.GREEN + str(msg) + color.END) +    except UnicodeEncodeError as e: +        print(msg) + + +def print_error(msg, channel=None): +    chstr = color.PURPLE + "[" + datetime.now().strftime( +        '%Y-%m-%d %H:%M:%S') + "] " + color.END +    chstr += color.CYAN + "[Channel : " + channel + \ +        "] " if channel is not None else "" + color.END +    try: +        print(chstr + color.RED + color.BOLD + str(msg) + color.END) +    except UnicodeEncodeError as e: +        print(msg) + +import threading + + +def kill_all_threads(): +    for thread in threading.enumerate(): +        if thread.isAlive(): +            thread._Thread__stop() + + +def get_input(message, t=None): +    while True: +        try: +            try: +                command = raw_input(message) +            except NameError: +                command = input(message) +            except KeyboardInterrupt: +                return None + +            command = command.strip() + +            if command is None or len(command) == 0: +                raise ValueError + +            if t is not None and t == bool: +                valid = ["True", "true", "1", 1, "y", "Y", "yes", "Yes", "YES"] +                if command in valid: +                    return True +                else: +                    return False +            if t is not None: +                command = t(command) +            else: +                command = eval("'" + command + "'") + +            return command +        except ValueError: +            print_error("Invalid input : " + command) + + +def _publish_command_handler(): + +    channel = get_input("[PUBLISH] Enter Channel Name ", str) +    if channel is None: +        return +    while True: +        message = get_input("[PUBLISH] Enter Message \ +            ( QUIT or CTRL-C for exit from publish mode ) ") +        if message == 'QUIT' or message == 'quit' or message is None: +            return + +        def _callback(r): +            print_ok(r) + +        def _error(r): +            print_error(r) +        pubnub.publish(channel, message, _callback, _error) + + +def _subscribe_command_handler(): +    channel = get_input("[SUBSCRIBE] Enter Channel Name ", str) + +    def _callback(r): +        print_ok(r, channel) + +    def _error(r): +        print_error(r, channel) +    pubnub.subscribe(channel, _callback, _error) + + +def _unsubscribe_command_handler(): +    channel = get_input("[UNSUBSCRIBE] Enter Channel Name ", str) + +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) +    pubnub.unsubscribe(channel) + + +def _grant_command_handler(): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) +    channel = get_input("[GRANT] Enter Channel Name ", str) +    auth_key = get_input("[GRANT] Enter Auth Key ", str) +    ttl = get_input("[GRANT] Enter ttl ", int) +    read = get_input("[GRANT] Read ? ", bool) +    write = get_input("[GRANT] Write ? ", bool) +    pubnub.grant(channel, auth_key, read, write, ttl, _callback) + + +def _revoke_command_handler(): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) +    channel = get_input("[REVOKE] Enter Channel Name ", str) +    auth_key = get_input("[REVOKE] Enter Auth Key ", str) +    ttl = get_input("[REVOKE] Enter ttl ", int) + +    pubnub.revoke(channel, auth_key, ttl, _callback) + + +def _audit_command_handler(): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) +    channel = get_input("[AUDIT] Enter Channel Name ", str) +    auth_key = get_input("[AUDIT] Enter Auth Key ", str) +    pubnub.audit(channel, auth_key, _callback) + + +def _history_command_handler(): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) +    channel = get_input("[HISTORY] Enter Channel Name ", str) +    count = get_input("[HISTORY] Enter Count ", int) + +    pubnub.history(channel, count, callback=_callback, error=_error) + + +def _here_now_command_handler(): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) +    channel = get_input("[HERE NOW] Enter Channel Name ", str) + +    pubnub.here_now(channel, callback=_callback, error=_error) + + +commands = [] +commands.append({"command": "publish", "handler": _publish_command_handler}) +commands.append( +    {"command": "subscribe", "handler": _subscribe_command_handler}) +commands.append( +    {"command": "unsubscribe", "handler": _unsubscribe_command_handler}) +commands.append( +    {"command": "here_now", "handler": _here_now_command_handler}) +commands.append({"command": "history", "handler": _history_command_handler}) +commands.append({"command": "grant", "handler": _grant_command_handler}) +commands.append({"command": "revoke", "handler": _revoke_command_handler}) +commands.append({"command": "audit", "handler": _audit_command_handler}) + +# last command is quit. add new commands before this line +commands.append({"command": "QUIT"}) + + +def get_help(): +    help = "" +    help += "Channels currently subscribed to : " +    help += str(pubnub.get_channel_array()) +    help += "\n" +    for i, v in enumerate(commands): +        help += "Enter " + str(i) + " for " + v['command'] + "\n" +    return help + + +while True: +    command = get_input(color.BLUE + get_help(), int) +    if command == len(commands) - 1 or command is None: +        kill_all_threads() +        break +    if command >= len(commands): +        print_error("Invalid input " + str(command)) +        continue + +    commands[command]['handler']() + +#pubnub.start() diff --git a/python/examples/here-now-example.py b/python/examples/here-now-example.py deleted file mode 100644 index d2ca9bd..0000000 --- a/python/examples/here-now-example.py +++ /dev/null @@ -1,37 +0,0 @@ -## www.pubnub.com - PubNub Real-time push service in the cloud.  -# coding=utf8 - -## PubNub Real-time Push APIs and Notifications Framework -## Copyright (c) 2010 Stephen Blum -## http://www.pubnub.com/ - -## ----------------------------------- -## PubNub 3.1 Real-time Push Cloud API -## ----------------------------------- - -import sys -sys.path.append('../') -from twisted.internet import reactor -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=publish_key, subscribe_key=subscribe_key, -    secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) -crazy  = 'hello_world' - -def print_cb(message): -	print message - -pubnub.here_now( { -    'channel'  : crazy, -    'callback' : print_cb -}) - diff --git a/python/examples/here-now.py b/python/examples/here-now.py new file mode 100644 index 0000000..9640cc5 --- /dev/null +++ b/python/examples/here-now.py @@ -0,0 +1,35 @@ +## 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/ + + +import sys +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=publish_key, subscribe_key=subscribe_key, +                secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) +channel = 'hello_world' + + +# Synchronous usage +print pubnub.here_now(channel) + +# Asynchronous usage + + +def callback(message): +    print(message) + +pubnub.here_now(channel, callback=callback, error=callback) diff --git a/python/examples/history-example.py b/python/examples/history-example.py deleted file mode 100755 index c7c9547..0000000 --- a/python/examples/history-example.py +++ /dev/null @@ -1,14 +0,0 @@ -import sys -sys.path.append('../') -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/examples/history.py b/python/examples/history.py new file mode 100644 index 0000000..603a0f8 --- /dev/null +++ b/python/examples/history.py @@ -0,0 +1,35 @@ +## 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/ + + +import sys +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=publish_key, subscribe_key=subscribe_key, +                secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) +channel = 'a' + +# Synchronous usage + +print pubnub.history(channel, count=2) + +# Asynchronous usage + + +def callback(message): +    print(message) + +pubnub.history(channel, count=2, callback=callback, error=callback) diff --git a/python/examples/publish-example.py b/python/examples/publish-example.py deleted file mode 100755 index c97034b..0000000 --- a/python/examples/publish-example.py +++ /dev/null @@ -1,14 +0,0 @@ -from Pubnub import Pubnub - -## Initiate Class -pubnub = Pubnub( publish_key='demo', subscribe_key='demo', ssl_on=False ) - -## Publish Example -info = pubnub.publish({ -    'channel' : 'hello_world', -    'message' : { -        'some_text' : 'Hello my World' -    } -}) -print(info) - diff --git a/python/examples/publish.py b/python/examples/publish.py new file mode 100644 index 0000000..594e7c4 --- /dev/null +++ b/python/examples/publish.py @@ -0,0 +1,36 @@ +## 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/ + + +import sys +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=publish_key, subscribe_key=subscribe_key, +                secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) +channel = 'hello_world' +message = 'Hello World !!!' + + +# Synchronous usage +print pubnub.publish(channel, message) + +# Asynchronous usage + + +def callback(message): +    print(message) + +pubnub.publish(channel, message, callback=callback, error=callback) diff --git a/python/examples/pubnub-console/pubnub-console b/python/examples/pubnub-console/pubnub-console new file mode 100644 index 0000000..058253f --- /dev/null +++ b/python/examples/pubnub-console/pubnub-console @@ -0,0 +1,691 @@ +#!/usr/bin/python + +## 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/ + + +import sys +from Pubnub import Pubnub +import threading +from datetime import datetime + +from cmd2 import Cmd, make_option, options, Cmd2TestCase +import optparse +import json + +import atexit +import os +import readline +import rlcompleter + +import pygments +from pygments.lexers import JsonLexer +from pygments.formatters import TerminalFormatter + +lexer = JsonLexer() +formatter = TerminalFormatter() +def highlight(msg): +    return pygments.highlight(msg, lexer, formatter) + + + +historyPath = os.path.expanduser("~/.pubnub_console_history") + + +def save_history(historyPath=historyPath): +    import readline +    readline.write_history_file(historyPath) + +if os.path.exists(historyPath): +    readline.read_history_file(historyPath) + +atexit.register(save_history) + +of = sys.stdout + +color = Cmd() + +stop = None + +full_date = False + + +def stop_2(th): +    th._Thread__stop() + + +def stop_3(th): +    th._stop() + + +def print_console_2(of, message): +    print >>of, message + + +def print_console_3(of, message): +    of.write(message) +    of.write("\n") + +print_console = None + +if type(sys.version_info) is tuple: +    print_console = print_console_2 +    stop = stop_2 +else: +    if sys.version_info.major == 2: +        print_console = print_console_2 +        stop = stop_2 +    else: +        print_console = print_console_3 +        stop = stop_3 + + +def get_date(): +    if full_date is True: +        return color.colorize(datetime.now().strftime( +            '%Y-%m-%d %H:%M:%S'), "magenta") +    else: +        return color.colorize(datetime.now().strftime( +            '%H:%M:%S'), "magenta") + +def print_ok_normal(msg, channel=None): +    if msg is None: +        return +    chstr = color.colorize("[" + get_date() + "] ", "magenta") +    chstr += color.colorize("[Channel : " + channel + +                            "] " if channel is not None else "", "cyan") +    try: +        print_console(of, (chstr + color.colorize(str(msg), "green"))) +    except UnicodeEncodeError as e: +        print_console(of, (msg)) + +    of.flush() + + +def print_error_normal(msg, channel=None): +    if msg is None: +        return +    chstr = color.colorize("[" + get_date() + "] ", "magenta") +    chstr += color.colorize("[Channel : " + channel + +                            "] " if channel is not None else "", "cyan") +    try: +        print_console(of, (chstr + color.colorize(color.colorize( +            str(msg), "red"), "bold"))) +    except UnicodeEncodeError as e: +        print_console(of, (msg)) +    of.flush() + +def print_ok_pretty(msg, channel=None): +    if msg is None: +        return +    chstr = color.colorize("[" + get_date() + "] ", "magenta") +    chstr += color.colorize("[Channel : " + channel + +                            "] " if channel is not None else "", "cyan") +    try: +        print_console(of, (chstr + highlight(json.dumps(msg, indent=2)))) +    except UnicodeEncodeError as e: +        print_console(of, (msg)) + +    of.flush() + + +def print_error_pretty(msg, channel=None): +    if msg is None: +        return +    chstr = color.colorize("[" + get_date() + "] ", "magenta") +    chstr += color.colorize("[Channel : " + channel + +                            "] " if channel is not None else "", "cyan") +    try: +        print_console(of, (chstr + color.colorize(color.colorize( +            "ERROR: ", "red"), "bold") + +            highlight(json.dumps(msg, indent=2)))) +    except UnicodeEncodeError as e: +        print_console(of, (msg)) +    of.flush() + +print_ok = print_ok_pretty +print_error = print_error_pretty + + +class DefaultPubnub(object): +    def handlerFunctionClosure(self, name): +        def handlerFunction(*args, **kwargs): +            print_error("Pubnub not initialized." + +                        "Use init command to initialize") +        return handlerFunction + +    def __getattr__(self, name): +        return self.handlerFunctionClosure(name) + +pubnub = DefaultPubnub() + + +def kill_all_threads(): +    for thread in threading.enumerate(): +        if thread.isAlive(): +            stop(thread) + + +def get_input(message, t=None): +    while True: +        try: +            try: +                command = raw_input(message) +            except NameError: +                command = input(message) +            except KeyboardInterrupt: +                return None + +            command = command.strip() + +            if command is None or len(command) == 0: +                raise ValueError + +            if t is not None and t == bool: +                valid = ["True", "true", "1", 1, "y", "Y", "yes", "Yes", "YES"] +                if command in valid: +                    return True +                else: +                    return False +            if t is not None: +                command = t(command) +            else: +                command = eval("'" + command + "'") + +            return command +        except ValueError: +            print_error("Invalid input : " + command) + + +def _publish_command_handler(channel, message, async=False): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) +    print_ok(pubnub.publish(channel, message, +                            _callback if async is True else None, +                            _error if async is True else None)) + + +def _subscribe_command_handler(channel): + +    def _callback(r, ch): +        print_ok(r, ch) + +    def _error(r, ch=None): +        print_error(r, ch if ch is not None else channel) + +    def _disconnect(r): +        print_error("DISCONNECTED", r) + +    def _reconnect(r): +        print_error("RECONNECTED", r) + +    def _connect(r): +        print_error("CONNECTED", r) + +    pubnub.subscribe(channel, _callback, _error, connect=_connect, +                     disconnect=_disconnect, reconnect=_reconnect) + + +def _unsubscribe_command_handler(channels): + +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) +    if not isinstance(channels, list): +        ch = [] +        ch.append(channels) +        channels = ch + +    for channel in channels: +        pubnub.unsubscribe(channel) +        pubnub.unsubscribe(channel + '-pnpres') +    print_ok('Unsubscribed from : ' + str(channels)) + + +def _grant_command_handler(channel, auth_key, read, write, ttl, async=False): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) + +    print_ok(pubnub.grant(channel, auth_key, +                          read, write, ttl, +                          _callback if async is True else None, +                          _error if async is True else None)) + + +def _revoke_command_handler(channel, auth_key, ttl, async=False): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) + +    print_ok(pubnub.revoke(channel, auth_key, ttl, +                           _callback if async is True else None, +                           _error if async is True else None)) + + +def _audit_command_handler(channel, auth_key, async=False): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) + +    print_ok(pubnub.audit(channel, auth_key, +                          _callback if async is True else None, +                          _error if async is True else None)) + + +def _history_command_handler(channel, count, async=False): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) + +    print_ok(pubnub.history(channel, count, +                            _callback if async is True else None, +                            _error if async is True else None)) + + +def _here_now_command_handler(channel, async=False): +    def _callback(r): +        print_ok(r) + +    def _error(r): +        print_error(r) + +    print_ok(pubnub.here_now(channel, _callback if async is True else None, +                             _error if async is True else None)) + + +def kill_all_threads(): +    for thread in threading.enumerate(): +        if thread.isAlive(): +            stop(thread) + + +def get_channel_array(): +    channels = pubnub.get_channel_array() + +    for channel in channels: +        if "-pnpres" in channel: +            i = channels.index(channel.split("-pnpres")[0]) +            channels[i] = channels[i] + color.colorize("(P)", "blue") +            channels.remove(channel) +    return channels + + +class DevConsole(Cmd): +    def __init__(self): +        Cmd.__init__(self) +        global pubnub +        self.intro = "For Help type ? or help . " + \ +            "To quit/exit type exit" +        self.default_channel = None +        self.async = False +        pubnub = Pubnub("demo", "demo") +        self.channel_truncation = 3 +        self.prompt = self.get_prompt() +        self.publish_key = "demo" +        self.subscribe_key = "demo" +        self.origin = "pubsub.pubnub.com" +        self.auth_key = None +        self.cipher_key = None +        self.secret_key = "demo" +        self.ssl = False +        self.uuid = None +        self.disable_pretty = False + +    def get_channel_origin(self): +        cho = " [" +        channels = get_channel_array() +        channels_str = ",".join(channels) +        sl = self.channel_truncation +        if len(channels) > int(sl) and int(sl) > 0: +            cho += ",".join(channels[:int(sl)]) + " " + str( +                len(channels) - int(sl)) + " more..." +        else: +            cho += ",".join(channels) + +        if len(channels) > 0: +            cho = color.colorize(cho, "bold") + "@" + +        origin = pubnub.get_origin().split("://")[1] +        origin += color.colorize(" (SSL)", "green") if pubnub.get_origin( +        ).split("://")[0] == "https" else "" +        return cho + color.colorize(origin, "blue") + "] > " + +    def get_prompt(self): +        prompt = "[" + get_date() + "]" + +        if self.default_channel is not None and len(self.default_channel) > 0: +            prompt += " [default channel: " + color.colorize( +                self.default_channel, "bold") + "]" + +        prompt += self.get_channel_origin() +        return prompt + +    def precmd(self, line): +        self.prompt = self.get_prompt() +        return line + +    #def emptyline(self): +    #    self.prompt = self.get_prompt() + +    def cmdloop_with_keyboard_interrupt(self): +        try: +            self.cmdloop() +        except KeyboardInterrupt as e: +            pass +        sys.stdout.write('\n') +        kill_all_threads() + +    @options([make_option('-p', '--publish-key', action="store", +                          default=None, help="Publish Key"), +              make_option('-s', '--subscribe-key', action="store", +                          default=None, help="Subscribe Key"), +              make_option('-k', '--secret-key', action="store", +                          default=None, help="cipher Key"), +              make_option('-c', '--cipher-key', action="store", +                          default=None, help="Secret Key"), +              make_option('-a', '--auth-key', action="store", +                          default=None, help="Auth Key"), +              make_option('--ssl-on', dest='ssl', action='store_true', +                          default=False, help="SSL Enabled ?"), +              make_option('-o', '--origin', action="store", +                          default=None, help="Origin"), +              make_option('-u', '--uuid', action="store", +                          default=None, help="UUID"), +              make_option('--disable-pretty-print', dest='disable_pretty', action='store_true', +                          default=False, help="Disable Pretty Print ?") +              ]) +    def do_init(self, command, opts): +        global pubnub +        global print_ok +        global print_error +        global print_ok_normal +        global print_error_normal +        global print_error_pretty +        global print_ok_pretty + +        self.publish_key = opts.publish_key if opts.publish_key is not None else self.publish_key +        self.subscribe_key = opts.subscribe_key if opts.subscribe_key is not None else self.subscribe_key +        self.secret_key = opts.secret_key if opts.secret_key is not None else self.secret_key +        self.cipher_key = opts.cipher_key if opts.cipher_key is not None else self.cipher_key +        self.auth_key = opts.auth_key if opts.auth_key is not None else self.auth_key +        self.origin = opts.origin if opts.origin is not None else self.origin +        self.uuid = opts.uuid if opts.uuid is not None else self.uuid +        self.ssl = opts.ssl if opts.ssl is not None else self.ssl +        self.disable_pretty = opts.disable_pretty if opts.disable_pretty is not None else self.disable_pretty + +        pubnub = Pubnub(self.publish_key, +                        self.subscribe_key, +                        self.secret_key, +                        self.cipher_key, +                        self.auth_key, +                        self.ssl, +                        self.origin, +                        self.uuid) +        self.prompt = self.get_prompt() + +        if opts.disable_pretty is True: +            print_ok = print_ok_normal +            print_error = print_error_normal +        else: +            print_ok = print_ok_pretty +            print_error = print_error_pretty + +    def do_set_sync(self, command): +        """unset_async +        Unset Async mode""" +        self.async = False + +    def do_set_async(self, command): +        """set_async +        Set Async mode""" +        self.async = True + +    @options([make_option('-n', '--count', action="store", +                          default=3, help="Number of channels on prompt") +              ]) +    def do_set_channel_truncation(self, command, opts): +        """set_channel_truncation +        Set Channel Truncation""" + +        self.channel_truncation = opts.count + +        self.prompt = self.get_prompt() + +    def do_unset_channel_truncation(self, command): +        """unset_channel_truncation +        Unset Channel Truncation""" +        self.channel_truncation = 0 +        self.prompt = self.get_prompt() + +    def do_set_full_date(self, command): +        global full_date +        """do_set_full_date +        Set Full Date""" +        full_date = True +        self.prompt = self.get_prompt() + +    def do_unset_full_date(self, command): +        global full_date +        """do_unset_full_date +        Unset Full Date""" +        full_date = False +        self.prompt = self.get_prompt() + +    @options([make_option('-c', '--channel', +                          action="store", help="Default Channel") +              ]) +    def do_set_default_channel(self, command, opts): + +        if opts.channel is None: +            print_error("Missing channel") +            return +        self.default_channel = opts.channel +        self.prompt = self.get_prompt() + +    @options([make_option('-f', '--file', action="store", +                          default="./pubnub-console.log", help="Output file") +              ]) +    def do_set_output_file(self, command, opts): +        global of +        try: +            of = file(opts.file, 'w+') +        except IOError as e: +            print_error("Could not set output file. " + e.reason) + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel for here now data") +              ]) +    def do_here_now(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel +        if opts.channel is None: +            print_error("Missing channel") +            return + +        _here_now_command_handler(opts.channel, async=self.async) + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel for history data"), +              make_option('-n', '--count', action="store", +                          default=5, help="Number of messages") +              ]) +    def do_get_history(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel +        if opts.channel is None: +            print_error("Missing channel") +            return + +        _history_command_handler(opts.channel, opts.count, async=self.async) + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel on which to publish") +              ]) +    def do_publish(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel +        if opts.channel is None: +            print_error("Missing channel") +            return + +        if command is None: +            print_error("Missing message") +            return + +        try: +            message = json.loads(str(command)) +        except ValueError as ve: +            message = str(command) + +        _publish_command_handler(opts.channel, message, async=self.async) + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel on which to grant"), +              make_option('-a', '--auth-key', dest="auth_key", +                          action="store", +                          help="Auth Key"), +              make_option('-r', '--read-enabled', dest='read', +                          action='store_true', +                          default=False, help="Read ?"), +              make_option('-w', '--write-enabled', dest='write', +                          action='store_true', +                          default=False, help="Write ?"), +              make_option('-t', '--ttl', action="store", +                          default=5, help="TTL"), +              make_option('-p', '--presence', action="store_true", +                          dest="presence", +                          default=False, help="Grant on presence channel ?") +              ]) +    def do_grant(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel + +        opts.auth_key = pubnub.auth_key \ +            if opts.auth_key is None else opts.auth_key + +        _grant_command_handler(opts.channel, opts.auth_key, +                               opts.read, opts.write, +                               opts.ttl, async=self.async) + +        if opts.presence is True: +            _grant_command_handler(opts.channel + '-pnpres', opts.auth_key, +                                   opts.read, opts.write, +                                   opts.ttl, async=self.async) + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel on which to revoke"), +              make_option('-a', '--auth-key', dest="auth_key", action="store", +                          help="Auth Key"), +              make_option('-t', '--ttl', action="store", +                          default=5, help="TTL"), +              make_option('-p', '--presence', action="store_true", +                          dest="presence", +                          default=False, help="Revoke on presence channel ?") +              ]) +    def do_revoke(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel + +        opts.auth_key = pubnub.auth_key \ +            if opts.auth_key is None else opts.auth_key + +        _revoke_command_handler( +            opts.channel, opts.auth_key, opts.ttl, async=self.async) + +        if opts.presence is True: +            _revoke_command_handler( +                opts.channel + '-pnpres', opts.auth_key, +                opts.ttl, async=self.async) + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel on which to revoke"), +              make_option('-a', '--auth-key', dest="auth_key", action="store", +                          help="Auth Key") +              ]) +    def do_audit(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel + +        opts.auth_key = pubnub.auth_key \ +            if opts.auth_key is None else opts.auth_key + +        _audit_command_handler(opts.channel, opts.auth_key, async=self.async) + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel for unsubscribe"), +              make_option('-a', '--all', action="store_true", dest="all", +                          default=False, help="Unsubscribe from all channels") +              ]) +    def do_unsubscribe(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel +        if (opts.all is True): +            opts.channel = pubnub.get_channel_array() +        if opts.channel is None: +            print_error("Missing channel") +            return +        _unsubscribe_command_handler(opts.channel) +        self.prompt = self.get_prompt() + +    @options([make_option('-c', '--channel', action="store", +                          help="Channel for subscribe"), +              make_option('-g', '--get-channel-list', action="store_true", +                          dest="get", +                          default=False, help="Get susbcribed channel list"), +              make_option('-p', '--presence', action="store_true", +                          dest="presence", +                          default=False, help="Presence events ?") +              ]) +    def do_subscribe(self, command, opts): +        opts.channel = self.default_channel \ +            if opts.channel is None else opts.channel +        if opts is None: +            print_error("Missing argument") +            return + +        if opts.channel is not None: +            _subscribe_command_handler(opts.channel) + +        if opts.presence is True: +            _subscribe_command_handler(opts.channel + '-pnpres') + +        if opts.get is True: +            print_ok(get_channel_array()) +        self.prompt = self.get_prompt() + +    def do_exit(self, args): +        kill_all_threads() +        return -1 + +    #def do_EOF(self, args): +    #    kill_all_threads() +    #    return self.do_exit(args) + +    #def handler(self, signum, frame): +    #    kill_all_threads() + + +def main(): +    app = DevConsole() +    app.cmdloop_with_keyboard_interrupt() + +if __name__ == "__main__": +    main() diff --git a/python/examples/pubnub-console/setup.py b/python/examples/pubnub-console/setup.py new file mode 100644 index 0000000..a9fa506 --- /dev/null +++ b/python/examples/pubnub-console/setup.py @@ -0,0 +1,27 @@ +from setuptools import setup, find_packages + +setup( +    name='pubnub-console', +    version='3.5.0', +    description='PubNub Developer Console', +    author='Stephen Blum', +    author_email='support@pubnub.com', +    url='http://pubnub.com', +    scripts=['pubnub-console'], +    license='MIT', +    classifiers=( +        'Development Status :: 5 - Production/Stable', +        'Intended Audience :: Developers', +        'Programming Language :: Python', +        'License :: OSI Approved :: MIT License', +        'Operating System :: OS Independent', +        'Topic :: Internet :: WWW/HTTP', +        'Topic :: Software Development :: Libraries :: Python Modules', +    ), +    install_requires=[ +        'pubnub>=3.5.0', +        'cmd2>=0.6.7', +        'pygments >= 1.6' +    ], +    zip_safe=False, +) diff --git a/python/examples/requirements.pip b/python/examples/requirements.pip new file mode 100644 index 0000000..738c606 --- /dev/null +++ b/python/examples/requirements.pip @@ -0,0 +1,3 @@ +pycrypto==2.6.1 +cmd2==0.6.7 +requests==2.2.1 diff --git a/python/examples/start-console.sh b/python/examples/start-console.sh new file mode 100755 index 0000000..a928cb3 --- /dev/null +++ b/python/examples/start-console.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +#!/bin/bash -e + +BASEDIR=. + +if [ ! -d "$BASEDIR/ve" ]; then +    virtualenv -q $BASEDIR/ve --no-site-packages +    $BASEDIR/ve/bin/activate +    echo "Virtualenv created." +fi + +chmod 755 $BASEDIR/ve/bin/activate +$BASEDIR/ve/bin/activate + +if [ ! -f "$BASEDIR/ve/updated" -o $BASEDIR/requirements.pip -nt $BASEDIR/ve/updated ]; then +    pip install -r $BASEDIR/requirements.pip -E $BASEDIR/ve +    touch $BASEDIR/ve/updated +    echo "Requirements installed." +fi + + + +if ! type "screen" > /dev/null; then +    echo "[ERROR] Screen is not installed. Please install screen to use this utility ." +    exit +fi +rm ./pubnub-console.log +touch ./pubnub-console.log +export PYTHONPATH=../.. +screen -X -S pubnub-console quit 2>&1 > /dev/null +OS="`uname`" +case $OS in +  [dD]'arwin') +	screen -c config_osx +    ;; +  *) screen -c config ;; +esac diff --git a/python/examples/subscribe-example.py b/python/examples/subscribe-example.py deleted file mode 100755 index 14a43d9..0000000 --- a/python/examples/subscribe-example.py +++ /dev/null @@ -1,65 +0,0 @@ -import sys -sys.path.append('../') -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/examples/subscribe.py b/python/examples/subscribe.py new file mode 100644 index 0000000..9b8b223 --- /dev/null +++ b/python/examples/subscribe.py @@ -0,0 +1,49 @@ +## 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/ + + +import sys +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=publish_key, subscribe_key=subscribe_key, +                secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) + +channel = 'a' + + +# Asynchronous usage +def callback(message, channel): +    print(message) + + +def error(message): +    print("ERROR : " + str(message)) + + +def connect(message): +    print("CONNECTED") + + +def reconnect(message): +    print("RECONNECTED") + + +def disconnect(message): +    print("DISCONNECTED") + + +pubnub.subscribe(channel, callback=callback, error=callback, +                 connect=connect, reconnect=reconnect, disconnect=disconnect) diff --git a/python/migration.md b/python/migration.md new file mode 100644 index 0000000..61cf203 --- /dev/null +++ b/python/migration.md @@ -0,0 +1,205 @@ +## Contact support@pubnub.com for all questions + +#### [PubNub](http://www.pubnub.com) Real-time Data Network +##### Standalone Python Migration + +#### Init + +``` + +# Pre 3.5: +pubnub = Pubnub( +    "demo",  ## PUBLISH_KEY +    "demo",  ## SUBSCRIBE_KEY +    False    ## SSL_ON? +) + +# New in 3.5+ +pubnub = Pubnub(publish_key="demo", subscribe_key="demo", ssl_on=False) + +``` + +#### PUBLISH + +``` +channel = 'hello_world' +message = 'Hello World !!!' + +# Pre 3.5: +info = pubnub.publish({ +    'channel' : channel, +    'message' : message +}) +print(info) + +# New in 3.5+ + +# Synchronous usage +print pubnub.publish(channel='hello_world', message='Hello World !!!') + +# Asynchronous usage + +def callback(message): +    print(message) + +pubnub.publish(channel, message, callback=callback, error=callback) + +``` + + +#### SUBSCRIBE +Pre 3.5.x, subscribe was blocking and would only be terminated via a false return from the callback. In our latest version of the SDK, subscribe is asyncronous, and because of this, usage is a bit different, but the experience is more like our other async SDKs. + +``` + +# Listen for Messages + +channel = 'hello_world' + +# Pre 3.5: +# Listen for Messages *BLOCKING* +def receive(message) : +    print(message) +    return True + +pubnub.subscribe({ +    'channel'  : channel, +    'callback' : receive  +}) + + +# New in 3.5+ + +def callback(message, channel): +    print(message) + + +def error(message): +    print("ERROR : " + str(message)) + + +def connect(message): +    print("CONNECTED") + + +def reconnect(message): +    print("RECONNECTED") + + +def disconnect(message): +    print("DISCONNECTED") + + +pubnub.subscribe(channel, callback=callback, error=callback, +                 connect=connect, reconnect=reconnect, disconnect=disconnect) +``` + +#### Unsubscribe +Once subscribed, you can easily, gracefully, unsubscribe: + +``` +# Pre 3.5: +# + +# New in 3.5+ + +pubnub.unsubscribe(channel='hello_world') +``` + +#### PRESENCE + +``` + + +channel = 'hello_world' + +# Pre 3.5: +def pres_event(message) : +    print(message) +    return True + +pubnub.presence({ +    'channel'  : channel, +    'callback' : receive  +}) + + +# New in 3.5+ + +# Listen for Presence Event Messages + +def callback(message, channel): +    print(message) + + +def error(message): +    print("ERROR : " + str(message)) + + + +pubnub.presence(channel, callback=callback, error=callback) +``` + +#### HERE_NOW + +``` + +# Pre 3.5: +# Get info on who is here right now! + +here_now = pubnub.here_now({ +    'channel' : 'hello_world', +}) + +print(here_now['occupancy']) +print(here_now['uuids']) + + +# New in 3.5+ + +# Get info on who is here right now! + +channel = 'hello_world' + +# Synchronous usage +print pubnub.here_now(channel) + + +# Asynchronous usage + +def callback(message): +    print(message) + +pubnub.here_now(channel, callback=callback, error=callback) +``` + +#### HISTORY + +``` + +# Pre 3.5: +# Load Previously Published Messages +history = pubnub.detailedHistory({ +    'channel'   : 'my_channel', +    'end'       : my_end_time_token, # Optional +    'start'     : my_start_time_token, # Optional +    'count'     : num_of_msgs_to_return # Optional, default is 100 +}) +print(history) + +# New in 3.5+ + +# Synchronous usage + +print pubnub.history(channel, count=2) + +# Asynchronous usage + + +def callback(message): +    print(message) + +pubnub.history(channel, count=2, callback=callback, error=callback) +``` + +## Contact support@pubnub.com for all questions diff --git a/python/tests/detailed-history-unit-test.py b/python/tests/detailed-history-unit-test.py deleted file mode 100755 index 31bdef8..0000000 --- a/python/tests/detailed-history-unit-test.py +++ /dev/null @@ -1,137 +0,0 @@ -## www.pubnub.com - PubNub Real-time push service in the cloud. -# coding=utf8 - -## PubNub Real-time Push APIs and Notifications Framework -## Copyright (c) 2010 Stephen Blum -## http://www.pubnub.com/ - -## ----------------------------------- -## PubNub 3.0 Real-time Push Cloud API -## ----------------------------------- - -import sys -sys.path.append('.') -sys.path.append('..') -sys.path.append('../common') -from Pubnub import Pubnub -import unittest2 as unittest - - -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/tests/subscribe-test.py b/python/tests/subscribe-test.py new file mode 100755 index 0000000..a1b1826 --- /dev/null +++ b/python/tests/subscribe-test.py @@ -0,0 +1,154 @@ +## 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 +from Pubnub import PubnubAsync as Pubnub +from functools import partial +from threading import current_thread +import threading +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 ) +pubnub = Pubnub(publish_key, subscribe_key, secret_key, ssl_on) +crazy = 'hello_world' + +current = -1 + +errors = 0 +received = 0 + +## ----------------------------------------------------------------------- +## Subscribe Example +## ----------------------------------------------------------------------- + + +def message_received(message): +    print(message) + + +def check_received(message): +    global current +    global errors +    global received +    print(message) +    print(current) +    if message <= current: +        print('ERROR') +        #sys.exit() +        errors += 1 +    else: +        received += 1 +    print('active thread count : ' + str(threading.activeCount())) +    print('errors = ' + str(errors)) +    print(current_thread().getName() + ' , ' + 'received = ' + str(received)) + +    if received != message: +        print('********** MISSED **************** ' + str(message - received)) +    current = message + + +def connected_test(ch): +    print('Connected ' + ch) + + +def connected(ch): +    pass + + +''' +pubnub.subscribe({ +    'channel'  : 'abcd1', +    'connect'  : connected, +    'callback' : message_received +}) +''' + + +def cb1(): +    pubnub.subscribe({ +        'channel': 'efgh1', +        'connect': connected, +        'callback': message_received +    }) + + +def cb2(): +    pubnub.subscribe({ +        'channel': 'dsm-test', +        'connect': connected_test, +        'callback': check_received +    }) + + +def cb3(): +    pubnub.unsubscribe({'channel': 'efgh1'}) + + +def cb4(): +    pubnub.unsubscribe({'channel': 'abcd1'}) + + +def subscribe(channel): +    pubnub.subscribe({ +        'channel': channel, +        'connect': connected, +        'callback': message_received +    }) + + +pubnub.timeout(15, cb1) + +pubnub.timeout(30, cb2) + + +pubnub.timeout(45, cb3) + +pubnub.timeout(60, cb4) + +#''' +for x in range(1, 1000): +    #print x +    def y(t): +        subscribe('channel-' + str(t)) + +    def z(t): +        pubnub.unsubscribe({'channel': 'channel-' + str(t)}) + +    pubnub.timeout(x + 5, partial(y, x)) +    pubnub.timeout(x + 25, partial(z, x)) +    x += 10 +#''' + +''' +for x in range(1,1000): +    def cb(r): print r , ' : ', threading.activeCount() +    def y(t): +        pubnub.publish({ +            'message' : t, +            'callback' : cb, +            'channel' : 'dsm-test' +        }) + + +    pubnub.timeout(x + 1, partial(y,x)) +    x += 1 +''' + + +pubnub.start() diff --git a/python/tests/test_grant.py b/python/tests/test_grant.py new file mode 100644 index 0000000..6826335 --- /dev/null +++ b/python/tests/test_grant.py @@ -0,0 +1,199 @@ + + +from Pubnub import Pubnub +import time + +pubnub = Pubnub("demo","demo") +pubnub_pam = Pubnub("pub-c-c077418d-f83c-4860-b213-2f6c77bde29a",  +	"sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe", "sec-c-OGU3Y2Q4ZWUtNDQwMC00NTI1LThjNWYtNWJmY2M4OGIwNjEy") + + +# Grant permission read true, write true, on channel ( Sync Mode ) +def test_1(): +	resp = pubnub_pam.grant(channel="abcd", auth_key="abcd", read=True, write=True, ttl=1) +	assert resp['message'] == 'Success' +	assert resp['payload'] == { +								'auths': {'abcd': {'r': 1, 'w': 1}}, +								'subscribe_key': 'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								'level': 'user', 'channel': 'abcd', 'ttl': 1 +							  } +							 + +# Grant permission read false, write false, on channel ( Sync Mode ) +def test_2(): +	resp = pubnub_pam.grant(channel="abcd", auth_key="abcd", read=False, write=False, ttl=1) +	assert resp['message'] == 'Success' +	assert resp['payload'] == { +								'auths': {'abcd': {'r': 0, 'w': 0}}, +								'subscribe_key': 'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								'level': 'user', 'channel': 'abcd', 'ttl': 1 +							  } + +# Grant permission read True, write false, on channel ( Sync Mode ) +def test_3(): +	resp = pubnub_pam.grant(channel="abcd", auth_key="abcd", read=True, write=False, ttl=1) +	assert resp['message'] == 'Success' +	assert resp['payload'] == { +								'auths': {'abcd': {'r': 1, 'w': 0}}, +								'subscribe_key': 'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								'level': 'user', 'channel': 'abcd', 'ttl': 1 +							  } + +# Grant permission read False, write True, on channel ( Sync Mode ) +def test_4(): +	resp = pubnub_pam.grant(channel="abcd", auth_key="abcd", read=True, write=False, ttl=1) +	assert resp['message'] == 'Success' +	assert resp['payload'] == { +								'auths': {'abcd': {'r': 1, 'w': 0}}, +								'subscribe_key': 'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								'level': 'user', 'channel': 'abcd', 'ttl': 1 +							  } + +# Grant permission read False, write True, on channel ( Sync Mode ), TTL 10 +def test_5(): +	resp = pubnub_pam.grant(channel="abcd", auth_key="abcd", read=True, write=False, ttl=10) +	assert resp['message'] == 'Success' +	assert resp['payload'] == { +								'auths': {'abcd': {'r': 1, 'w': 0}}, +								'subscribe_key': 'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								'level': 'user', 'channel': 'abcd', 'ttl': 10 +							  } + +# Grant permission read False, write True, without channel ( Sync Mode ), TTL 10 +def test_6(): +	resp = pubnub_pam.grant(auth_key="abcd", read=True, write=False, ttl=10) +	assert resp['message'] == 'Success' +	assert resp['payload'] == { +								'subscribe_key': 'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								'level': 'subkey' , u'r': 1, u'w': 0, 'ttl': 10 +							  } + + +# Grant permission read False, write False, without channel ( Sync Mode ) +def test_7(): +	resp = pubnub_pam.grant(auth_key="abcd", read=False, write=False) +	assert resp['message'] == 'Success' +	assert resp['payload'] == { +								'subscribe_key': 'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								'level': 'subkey' , u'r': 0, u'w': 0, 'ttl': 1 +							  } + + +# Complete flow , try publish on forbidden channel, grant permission to auth key and try again. ( Sync Mode) + +def test_8(): +	channel = "test_8-" + str(time.time()) +	message = "Hello World" +	auth_key = "auth-" + channel +	pubnub_pam.set_auth_key(auth_key) +	resp = pubnub_pam.publish(channel=channel,message=message) +	assert resp['message'] == 'Forbidden' +	assert resp['payload'] == {u'channels': [channel]} +	resp = pubnub_pam.grant(channel=channel, read=True, write=True, auth_key=auth_key, ttl=10) +	assert resp == 			{ +								'message': u'Success', +								'payload': {u'auths': {auth_key : {u'r': 1, u'w': 1}}, +								u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								u'level': u'user', u'channel': channel, u'ttl': 10} +							} +	resp = pubnub_pam.publish(channel=channel,message=message) +	assert resp[0] == 1 + + +# Complete flow , try publish on forbidden channel, grant permission to authkey and try again. ( Sync Mode) +# then revoke and try again +def test_9(): +	channel = "test_9-" + str(time.time()) +	message = "Hello World" +	auth_key = "auth-" + channel +	pubnub_pam.set_auth_key(auth_key) +	resp = pubnub_pam.publish(channel=channel,message=message) +	assert resp['message'] == 'Forbidden' +	assert resp['payload'] == {u'channels': [channel]} +	resp = pubnub_pam.grant(channel=channel, read=True, write=True, auth_key=auth_key, ttl=10) +	print resp +	assert resp == 			{ +								'message': u'Success', +								'payload': {u'auths': {auth_key : {u'r': 1, u'w': 1}}, +								u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								u'level': u'user', u'channel': channel, u'ttl': 10} +							} +	resp = pubnub_pam.publish(channel=channel,message=message) +	assert resp[0] == 1 +	resp = pubnub_pam.revoke(channel=channel, auth_key=auth_key) +	print resp +	assert resp == 			{ +								'message': u'Success', +								'payload': {u'auths': {auth_key : {u'r': 0, u'w': 0}}, +								u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								u'level': u'user', u'channel': channel, u'ttl': 1} +							} +	resp = pubnub_pam.publish(channel=channel,message=message) +	assert resp['message'] == 'Forbidden' +	assert resp['payload'] == {u'channels': [channel]} + +# Complete flow , try publish on forbidden channel, grant permission channel level for subkey and try again. ( Sync Mode) +# then revoke and try again +def test_10(): +	channel = "test_10-" + str(time.time()) +	message = "Hello World" +	auth_key = "auth-" + channel +	pubnub_pam.set_auth_key(auth_key) +	resp = pubnub_pam.publish(channel=channel,message=message) +	assert resp['message'] == 'Forbidden' +	assert resp['payload'] == {u'channels': [channel]} +	resp = pubnub_pam.grant(channel=channel, read=True, write=True, ttl=10) +	print resp +	assert resp == 			{ +									'message': u'Success', +									'payload': { u'channels': {channel: {u'r': 1, u'w': 1}}, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'channel', u'ttl': 10} +								} +	resp = pubnub_pam.publish(channel=channel,message=message) +	assert resp[0] == 1 +	resp = pubnub_pam.revoke(channel=channel) +	print resp +	assert resp == 			{ +									'message': u'Success', +									'payload': { u'channels': {channel : {u'r': 0, u'w': 0}}, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'channel', u'ttl': 1} +								} +	resp = pubnub_pam.publish(channel=channel,message=message) +	assert resp['message'] == 'Forbidden' +	assert resp['payload'] == {u'channels': [channel]} + +# Complete flow , try publish on forbidden channel, grant permission subkey level for subkey and try again. ( Sync Mode) +# then revoke and try again +def test_11(): +	channel = "test_11-" + str(time.time()) +	message = "Hello World" +	auth_key = "auth-" + channel +	pubnub_pam.set_auth_key(auth_key) +	resp = pubnub_pam.publish(channel=channel,message=message) +	assert resp['message'] == 'Forbidden' +	assert resp['payload'] == {u'channels': [channel]} +	resp = pubnub_pam.grant(read=True, write=True, ttl=10) +	print resp +	assert resp == 			{ +									'message': u'Success', +									'payload': { u'r': 1, u'w': 1, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'subkey', u'ttl': 10} +								} +	resp = pubnub_pam.publish(channel=channel,message=message) +	assert resp[0] == 1 +	resp = pubnub_pam.revoke() +	print resp +	assert resp == 			{ +									'message': u'Success', +									'payload': {u'r': 0, u'w': 0, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'subkey', u'ttl': 1} +								} +	resp = pubnub_pam.publish(channel=channel,message=message) +	assert resp['message'] == 'Forbidden' +	assert resp['payload'] == {u'channels': [channel]} + + diff --git a/python/tests/test_grant_async.py b/python/tests/test_grant_async.py new file mode 100644 index 0000000..4d38a0a --- /dev/null +++ b/python/tests/test_grant_async.py @@ -0,0 +1,369 @@ + + +from Pubnub import Pubnub +import time + +pubnub = Pubnub("demo","demo") +pubnub_pam = Pubnub("pub-c-c077418d-f83c-4860-b213-2f6c77bde29a",  +	"sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe", "sec-c-OGU3Y2Q4ZWUtNDQwMC00NTI1LThjNWYtNWJmY2M4OGIwNjEy") + + + +# Grant permission read true, write true, on channel ( Async Mode ) +def test_1(): +	resp = {'response' : None} +	def _callback(response): +		resp['response'] = response + +	def _error(response): +		resp['response'] = response + +	pubnub_pam.grant(channel="abcd", auth_key="abcd", read=True, write=True, ttl=1, callback=_callback, error=_error) +	time.sleep(2) +	assert resp['response'] == { +									'message': u'Success', +									'payload': {u'auths': {u'abcd': {u'r': 1, u'w': 1}}, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'user', u'channel': u'abcd', u'ttl': 1} +								} +							 + +# Grant permission read false, write false, on channel ( Async Mode ) +def test_2(): +	resp = {'response' : None} +	def _callback(response): +		resp['response'] = response + +	def _error(response): +		resp['response'] = response + +	pubnub_pam.grant(channel="abcd", auth_key="abcd", read=False, write=False, ttl=1, callback=_callback, error=_error) +	time.sleep(2) +	assert resp['response'] == { +									'message': u'Success', +									'payload': {u'auths': {u'abcd': {u'r': 0, u'w': 0}}, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'user', u'channel': u'abcd', u'ttl': 1} +								} + + +# Grant permission read True, write false, on channel ( Async Mode ) +def test_3(): +	resp = {'response' : None} +	def _callback(response): +		resp['response'] = response + +	def _error(response): +		resp['response'] = response + +	pubnub_pam.grant(channel="abcd", auth_key="abcd", read=True, write=False, ttl=1, callback=_callback, error=_error) +	time.sleep(2) +	assert resp['response'] == { +									'message': u'Success', +									'payload': {u'auths': {u'abcd': {u'r': 1, u'w': 0}}, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'user', u'channel': u'abcd', u'ttl': 1} +								} + +# Grant permission read False, write True, on channel ( Async Mode ) +def test_4(): +	resp = {'response' : None} +	def _callback(response): +		resp['response'] = response + +	def _error(response): +		resp['response'] = response + +	pubnub_pam.grant(channel="abcd", auth_key="abcd", read=False, write=True, ttl=1, callback=_callback, error=_error) +	time.sleep(2) +	assert resp['response'] == { +									'message': u'Success', +									'payload': {u'auths': {u'abcd': {u'r': 0, u'w': 1}}, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'user', u'channel': u'abcd', u'ttl': 1} +								} + + +# Grant permission read False, write True, on channel ( Async Mode ), TTL 10 +def test_5(): +	resp = {'response' : None} +	def _callback(response): +		resp['response'] = response + +	def _error(response): +		resp['response'] = response + +	pubnub_pam.grant(channel="abcd", auth_key="abcd", read=False, write=True, ttl=10, callback=_callback, error=_error) +	time.sleep(2) +	assert resp['response'] == { +									'message': u'Success', +									'payload': {u'auths': {u'abcd': {u'r': 0, u'w': 1}}, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'user', u'channel': u'abcd', u'ttl': 10} +								} + + +# Grant permission read False, write True, without channel ( Async Mode ), TTL 10 +def test_6(): +	resp = {'response' : None} +	def _callback(response): +		resp['response'] = response + +	def _error(response): +		resp['response'] = response + +	pubnub_pam.grant(auth_key="abcd", read=False, write=True, ttl=10, callback=_callback, error=_error) +	time.sleep(2) +	assert resp['response'] == { +									'message': u'Success', +									'payload': { u'r': 0, u'w': 1, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'subkey', u'ttl': 10} +								} + + +# Grant permission read False, write False, without channel ( Async Mode ) +def test_7(): +	resp = {'response' : None} +	def _callback(response): +		resp['response'] = response + +	def _error(response): +		resp['response'] = response + +	pubnub_pam.grant(auth_key="abcd", read=False, write=False, callback=_callback, error=_error) +	time.sleep(2) +	assert resp['response'] == { +									'message': u'Success', +									'payload': { u'r': 0, u'w': 0, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'subkey', u'ttl': 1} +								} + + +# Complete flow , try publish on forbidden channel, grant permission to subkey and try again. ( Sync Mode) + +def test_8(): +	channel = "test_8-" + str(time.time()) +	message = "Hello World" +	auth_key = "auth-" + channel +	pubnub_pam.set_auth_key(auth_key) + + + +	def _cb1(resp, ch=None): +		assert False +	def _err1(resp): +		assert resp['message'] == 'Forbidden' +		assert resp['payload'] == {u'channels': [channel]} +	pubnub_pam.publish(channel=channel,message=message, callback=_cb1, error=_err1) +	time.sleep(2) + + +	def _cb2(resp, ch=None): +		assert resp == 		{ +								'message': u'Success', +								'payload': {u'auths': {auth_key : {u'r': 1, u'w': 1}}, +								u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								u'level': u'user', u'channel': channel, u'ttl': 10} +							} +	def _err2(resp): +		assert False + + +	resp = pubnub_pam.grant(channel=channel, read=True, write=True, auth_key=auth_key, ttl=10, callback=_cb2, error=_err2) +	time.sleep(2) + +	def _cb3(resp, ch=None): +		assert resp[0] == 1 +	def _err3(resp): +		assert False + +	pubnub_pam.publish(channel=channel,message=message, callback=_cb3, error=_err3) +	time.sleep(2) + + + + + +# Complete flow , try publish on forbidden channel, grant permission to authkey and try again.  +# then revoke and try again +def test_9(): +	channel = "test_9-" + str(time.time()) +	message = "Hello World" +	auth_key = "auth-" + channel +	pubnub_pam.set_auth_key(auth_key) + +	def _cb1(resp, ch=None): +		assert False +	def _err1(resp): +		assert resp['message'] == 'Forbidden' +		assert resp['payload'] == {u'channels': [channel]} +	pubnub_pam.publish(channel=channel,message=message, callback=_cb1, error=_err1) +	time.sleep(2) + + +	def _cb2(resp, ch=None): +		assert resp == 		{ +								'message': u'Success', +								'payload': {u'auths': {auth_key : {u'r': 1, u'w': 1}}, +								u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								u'level': u'user', u'channel': channel, u'ttl': 10} +							} +	def _err2(resp): +		assert False + + +	pubnub_pam.grant(channel=channel, read=True, write=True, auth_key=auth_key, ttl=10, callback=_cb2, error=_err2) +	time.sleep(2) + +	def _cb3(resp, ch=None): +		assert resp[0] == 1 +	def _err3(resp): +		assert False + +	pubnub_pam.publish(channel=channel,message=message, callback=_cb3, error=_err3) +	time.sleep(2) + +	def _cb4(resp, ch=None): +		assert resp == 		{ +								'message': u'Success', +								'payload': {u'auths': {auth_key : {u'r': 0, u'w': 0}}, +								u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								u'level': u'user', u'channel': channel, u'ttl': 1} +							} +	def _err4(resp): +		assert False +	pubnub_pam.revoke(channel=channel, auth_key=auth_key, callback=_cb4, error=_err4) +	time.sleep(2) + +	def _cb5(resp, ch=None): +		assert False +	def _err5(resp): +		assert resp['message'] == 'Forbidden' +		assert resp['payload'] == {u'channels': [channel]} +	pubnub_pam.publish(channel=channel,message=message, callback=_cb5, error=_err5) +	time.sleep(2) + + + + +# Complete flow , try publish on forbidden channel, grant permission channel level for subkey and try again. +# then revoke and try again +def test_10(): +	channel = "test_10-" + str(time.time()) +	message = "Hello World" +	auth_key = "auth-" + channel +	pubnub_pam.set_auth_key(auth_key) + +	def _cb1(resp, ch=None): +		assert False +	def _err1(resp): +		assert resp['message'] == 'Forbidden' +		assert resp['payload'] == {u'channels': [channel]} +	pubnub_pam.publish(channel=channel,message=message, callback=_cb1, error=_err1) +	time.sleep(2) + + +	def _cb2(resp, ch=None): +		assert resp == 		{ +									'message': u'Success', +									'payload': { u'channels': {channel: {u'r': 1, u'w': 1}}, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'channel', u'ttl': 10} +								} +	def _err2(resp): +		assert False + + +	pubnub_pam.grant(channel=channel, read=True, write=True, ttl=10, callback=_cb2, error=_err2) +	time.sleep(2) + +	def _cb3(resp, ch=None): +		assert resp[0] == 1 +	def _err3(resp): +		assert False + +	pubnub_pam.publish(channel=channel,message=message, callback=_cb3, error=_err3) +	time.sleep(2) + +	def _cb4(resp, ch=None): +		assert resp == 		{ +									'message': u'Success', +									'payload': { u'channels': {channel : {u'r': 0, u'w': 0}}, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'channel', u'ttl': 1} +								} +	def _err4(resp): +		assert False +	pubnub_pam.revoke(channel=channel, callback=_cb4, error=_err4) +	time.sleep(2) + +	def _cb5(resp, ch=None): +		assert False +	def _err5(resp): +		assert resp['message'] == 'Forbidden' +		assert resp['payload'] == {u'channels': [channel]} +	pubnub_pam.publish(channel=channel,message=message, callback=_cb5, error=_err5) +	time.sleep(2) + + + +# Complete flow , try publish on forbidden channel, grant permission subkey level for subkey and try again. +# then revoke and try again +def test_11(): +	channel = "test_11-" + str(time.time()) +	message = "Hello World" +	auth_key = "auth-" + channel +	pubnub_pam.set_auth_key(auth_key) + +	def _cb1(resp, ch=None): +		assert False +	def _err1(resp): +		assert resp['message'] == 'Forbidden' +		assert resp['payload'] == {u'channels': [channel]} +	pubnub_pam.publish(channel=channel,message=message, callback=_cb1, error=_err1) +	time.sleep(2) + + +	def _cb2(resp, ch=None): +		assert resp == 		{ +									'message': u'Success', +									'payload': { u'r': 1, u'w': 1, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'subkey', u'ttl': 10} +								} +	def _err2(resp): +		assert False + + +	pubnub_pam.grant(read=True, write=True, ttl=10, callback=_cb2, error=_err2) +	time.sleep(2) + +	def _cb3(resp, ch=None): +		assert resp[0] == 1 +	def _err3(resp): +		assert False + +	pubnub_pam.publish(channel=channel,message=message, callback=_cb3, error=_err3) +	time.sleep(2) + +	def _cb4(resp, ch=None): +		assert resp == 		{ +									'message': u'Success', +									'payload': {u'r': 0, u'w': 0, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'subkey', u'ttl': 1} +								} +	def _err4(resp): +		assert False +	pubnub_pam.revoke(callback=_cb4, error=_err4) +	time.sleep(2) + +	def _cb5(resp, ch=None): +		assert False +	def _err5(resp): +		assert resp['message'] == 'Forbidden' +		assert resp['payload'] == {u'channels': [channel]} +	pubnub_pam.publish(channel=channel,message=message, callback=_cb5, error=_err5) +	time.sleep(2) diff --git a/python/tests/test_publish_async.py b/python/tests/test_publish_async.py new file mode 100644 index 0000000..7270727 --- /dev/null +++ b/python/tests/test_publish_async.py @@ -0,0 +1,228 @@ + + +from Pubnub import Pubnub +import time + +pubnub = Pubnub("demo","demo") +pubnub_enc = Pubnub("demo", "demo", cipher_key="enigma") +pubnub_pam = Pubnub("pub-c-c077418d-f83c-4860-b213-2f6c77bde29a",  +	"sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe", "sec-c-OGU3Y2Q4ZWUtNDQwMC00NTI1LThjNWYtNWJmY2M4OGIwNjEy") + + + +# Publish and receive string +def test_1(): + +	channel = "test_1-" + str(time.time()) +	message = "I am a string" + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub.unsubscribe(channel) + +	def _connect(resp): +		pubnub.publish(channel,message) + +	def _error(resp): +		assert False + +	pubnub.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive array +def test_2(): + +	channel = "test_2-" + str(time.time()) +	message = [1,2] + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub.unsubscribe(channel) + +	def _connect(resp): +		pubnub.publish(channel,message) + +	def _error(resp): +		assert False + +	pubnub.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive json object +def test_3(): + +	channel = "test_2-" + str(time.time()) +	message = { "a" : "b" } + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub.unsubscribe(channel) + +	def _connect(resp): +		pubnub.publish(channel,message) + +	def _error(resp): +		assert False + +	pubnub.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive number +def test_4(): + +	channel = "test_2-" + str(time.time()) +	message = 100 + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub.unsubscribe(channel) + +	def _connect(resp): +		pubnub.publish(channel,message) + +	def _error(resp): +		assert False + +	pubnub.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive number string +def test_5(): + +	channel = "test_5-" + str(time.time()) +	message = "100" + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub.unsubscribe(channel) + +	def _connect(resp): +		pubnub.publish(channel,message) + +	def _error(resp): +		assert False + +	pubnub.subscribe(channel, callback=_cb, connect=_connect, error=_error) + + +# Publish and receive string (Encryption enabled) +def test_6(): + +	channel = "test_6-" + str(time.time()) +	message = "I am a string" + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub_enc.unsubscribe(channel) + +	def _connect(resp): +		pubnub_enc.publish(channel,message) + +	def _error(resp): +		assert False + +	pubnub_enc.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive array (Encryption enabled) +def test_7(): + +	channel = "test_7-" + str(time.time()) +	message = [1,2] + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub_enc.unsubscribe(channel) + +	def _connect(resp): +		pubnub.publish(channel,message) + +	def _error(resp): +		assert False + +	pubnub.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive json object (Encryption enabled) +def test_8(): + +	channel = "test_8-" + str(time.time()) +	message = { "a" : "b" } + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub_enc.unsubscribe(channel) + +	def _connect(resp): +		pubnub_enc.publish(channel,message) + +	def _error(resp): +		assert False + +	pubnub_enc.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive number (Encryption enabled) +def test_9(): + +	channel = "test_9-" + str(time.time()) +	message = 100 + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub_enc.unsubscribe(channel) + +	def _connect(resp): +		pubnub_enc.publish(channel,message) + +	def _error(resp): +		assert False + +	pubnub_enc.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive number string (Encryption enabled) +def test_10(): + +	channel = "test_10-" + str(time.time()) +	message = "100" + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub_enc.unsubscribe(channel) + +	def _connect(resp): +		pubnub_enc.publish(channel,message) + +	def _error(resp): +		assert False + +	pubnub_enc.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive object string (Encryption enabled) +def test_11(): + +	channel = "test_11-" + str(time.time()) +	message = '{"a" : "b"}' + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub_enc.unsubscribe(channel) + +	def _connect(resp): +		pubnub_enc.publish(channel,message) + +	def _error(resp): +		assert False + +	pubnub_enc.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive array string (Encryption enabled) +def test_12(): + +	channel = "test_12-" + str(time.time()) +	message = '[1,2]' + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub_enc.unsubscribe(channel) + +	def _connect(resp): +		pubnub_enc.publish(channel,message) + +	def _error(resp): +		assert False + +	pubnub_enc.subscribe(channel, callback=_cb, connect=_connect, error=_error) diff --git a/python/tests/unit-test.py b/python/tests/unit-test.py deleted file mode 100755 index 1737ace..0000000 --- a/python/tests/unit-test.py +++ /dev/null @@ -1,66 +0,0 @@ -## www.pubnub.com - PubNub Real-time push service in the cloud.  -# coding=utf8 - -## PubNub Real-time Push APIs and Notifications Framework -## Copyright (c) 2010 Stephen Blum -## http://www.pubnub.com/ - -## ----------------------------------- -## PubNub 3.0 Real-time Push Cloud API -## ----------------------------------- - -import sys -sys.path.append('.') -sys.path.append('..') -sys.path.append('../common') -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 -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  = 'demo' - -## --------------------------------------------------------------------------- -## Unit Test Function -## --------------------------------------------------------------------------- -def test( trial, name ) : -    if trial : -        print( 'PASS: ' + name ) -    else : -        print( 'FAIL: ' + name ) - -## ----------------------------------------------------------------------- -## Publish Example -## ----------------------------------------------------------------------- -publish_success = pubnub.publish({ -    'channel' : crazy, -    'message' : crazy -}) -test( publish_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) ) diff --git a/python/unassembled/Platform.py b/python/unassembled/Platform.py deleted file mode 100644 index f598a98..0000000 --- a/python/unassembled/Platform.py +++ /dev/null @@ -1,40 +0,0 @@ - -class Pubnub(PubnubCore): -    def __init__( -        self, -        publish_key, -        subscribe_key, -        secret_key = False, -        cipher_key = False, -        ssl_on = False, -        origin = 'pubsub.pubnub.com', -        pres_uuid = None -    ) : -        super(Pubnub, self).__init__( -            publish_key = publish_key, -            subscribe_key = subscribe_key, -            secret_key = secret_key, -            cipher_key = cipher_key, -            ssl_on = ssl_on, -            origin = origin, -            uuid = pres_uuid -        )         - -    def _request( self, request, callback = None ) : -        ## Build URL -        url = self.getUrl(request) - -        ## Send Request Expecting JSONP Response -        try: -            try: usock = urllib2.urlopen( url, None, 310 ) -            except TypeError: usock = urllib2.urlopen( url, None ) -            response = usock.read() -            usock.close() -            resp_json = json.loads(response) -        except: -            return None -             -        if (callback): -            callback(resp_json) -        else: -            return resp_json | 
