diff options
Diffstat (limited to 'python/examples')
| -rw-r--r-- | python/examples/config | 9 | ||||
| -rw-r--r-- | python/examples/config_osx | 8 | ||||
| -rw-r--r-- | python/examples/console-help.txt | 37 | ||||
| -rw-r--r-- | python/examples/console.py | 689 | ||||
| -rwxr-xr-x | python/examples/dev-console.py | 278 | ||||
| -rw-r--r-- | python/examples/here-now-example.py | 37 | ||||
| -rw-r--r-- | python/examples/here-now.py | 35 | ||||
| -rwxr-xr-x | python/examples/history-example.py | 14 | ||||
| -rw-r--r-- | python/examples/history.py | 35 | ||||
| -rwxr-xr-x | python/examples/publish-example.py | 14 | ||||
| -rw-r--r-- | python/examples/publish.py | 36 | ||||
| -rw-r--r-- | python/examples/pubnub-console/pubnub-console | 691 | ||||
| -rw-r--r-- | python/examples/pubnub-console/setup.py | 27 | ||||
| -rw-r--r-- | python/examples/requirements.pip | 3 | ||||
| -rwxr-xr-x | python/examples/start-console.sh | 38 | ||||
| -rwxr-xr-x | python/examples/subscribe-example.py | 65 | ||||
| -rw-r--r-- | python/examples/subscribe.py | 49 | 
17 files changed, 1935 insertions, 130 deletions
| 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) | 
