From 928c7bad652b406a2eade03bf1f72e1ddbb1f6c3 Mon Sep 17 00:00:00 2001 From: hushasha Date: Wed, 9 Nov 2016 16:18:58 +0800 Subject: [PATCH] First --- python-tornado/LICENSE | 27 + python-tornado/README.md | 137 ++++ python-tornado/examples/audit.py | 35 + python-tornado/examples/grant.py | 35 + python-tornado/examples/here-now.py | 36 + python-tornado/examples/history.py | 37 + python-tornado/examples/presence_group.py | 67 ++ python-tornado/examples/publish.py | 36 + python-tornado/examples/revoke.py | 35 + python-tornado/examples/subscribe.py | 52 ++ python-tornado/examples/subscribe_group.py | 69 ++ python-tornado/migration.md | 205 +++++ python-tornado/tests/test_grant_async.py | 354 +++++++++ python-tornado/tests/test_publish_async.py | 333 ++++++++ python-twisted/LICENSE | 27 + python-twisted/README.md | 137 ++++ python-twisted/examples/audit.py | 35 + python-twisted/examples/echo-client.py | 99 +++ python-twisted/examples/echo-server.py | 104 +++ python-twisted/examples/grant.py | 35 + python-twisted/examples/here-now.py | 35 + python-twisted/examples/history.py | 35 + python-twisted/examples/publish.py | 36 + python-twisted/examples/revoke.py | 35 + python-twisted/examples/subscribe.py | 52 ++ python-twisted/examples/subscribe_group.py | 54 ++ python-twisted/migration.md | 205 +++++ python-twisted/tests/benchmark.py | 90 +++ python-twisted/tests/delivery.py | 168 ++++ python-twisted/tests/subscribe-test.py | 156 ++++ python-twisted/tests/test_grant_async.py | 365 +++++++++ python-twisted/tests/test_publish_async.py | 333 ++++++++ python-twisted/tests/unit-test-full.py | 230 ++++++ python/LICENSE | 27 + python/README.md | 400 ++++++++++ python/examples/audit.py | 35 + python/examples/config | 9 + python/examples/config_osx | 8 + python/examples/console-help.txt | 37 + python/examples/console.py | 719 +++++++++++++++++ python/examples/cr.py | 52 ++ python/examples/dev-console.py | 273 +++++++ python/examples/grant.py | 35 + python/examples/heartbeat.py | 106 +++ python/examples/here-now.py | 35 + python/examples/history.py | 47 ++ python/examples/pam_demo/demo.py | 126 +++ python/examples/presence.py | 32 + python/examples/publish.py | 36 + python/examples/pubnub-console/pubnub-console | 724 ++++++++++++++++++ python/examples/pubnub-console/setup.py | 27 + python/examples/requirements.pip | 3 + python/examples/revoke.py | 35 + python/examples/start-console.sh | 38 + python/examples/state.py | 123 +++ python/examples/subscribe.py | 53 ++ python/examples/subscribe_group.py | 69 ++ python/examples/where-now.py | 38 + python/examples/wildcard_subscribe.py | 96 +++ python/migration.md | 205 +++++ python/tests/test_cg.py | 96 +++ python/tests/test_grant.py | 90 +++ python/tests/test_history.py | 65 ++ python/tests/test_wildcard.py | 360 +++++++++ 64 files changed, 7688 insertions(+) create mode 100644 python-tornado/LICENSE create mode 100644 python-tornado/README.md create mode 100644 python-tornado/examples/audit.py create mode 100644 python-tornado/examples/grant.py create mode 100644 python-tornado/examples/here-now.py create mode 100644 python-tornado/examples/history.py create mode 100644 python-tornado/examples/presence_group.py create mode 100644 python-tornado/examples/publish.py create mode 100644 python-tornado/examples/revoke.py create mode 100644 python-tornado/examples/subscribe.py create mode 100644 python-tornado/examples/subscribe_group.py create mode 100644 python-tornado/migration.md create mode 100644 python-tornado/tests/test_grant_async.py create mode 100644 python-tornado/tests/test_publish_async.py create mode 100644 python-twisted/LICENSE create mode 100644 python-twisted/README.md create mode 100644 python-twisted/examples/audit.py create mode 100644 python-twisted/examples/echo-client.py create mode 100644 python-twisted/examples/echo-server.py create mode 100644 python-twisted/examples/grant.py create mode 100644 python-twisted/examples/here-now.py create mode 100644 python-twisted/examples/history.py create mode 100644 python-twisted/examples/publish.py create mode 100644 python-twisted/examples/revoke.py create mode 100644 python-twisted/examples/subscribe.py create mode 100644 python-twisted/examples/subscribe_group.py create mode 100644 python-twisted/migration.md create mode 100644 python-twisted/tests/benchmark.py create mode 100644 python-twisted/tests/delivery.py create mode 100644 python-twisted/tests/subscribe-test.py create mode 100644 python-twisted/tests/test_grant_async.py create mode 100644 python-twisted/tests/test_publish_async.py create mode 100644 python-twisted/tests/unit-test-full.py create mode 100644 python/LICENSE create mode 100644 python/README.md create mode 100644 python/examples/audit.py create mode 100644 python/examples/config create mode 100644 python/examples/config_osx create mode 100644 python/examples/console-help.txt create mode 100644 python/examples/console.py create mode 100644 python/examples/cr.py create mode 100644 python/examples/dev-console.py create mode 100644 python/examples/grant.py create mode 100644 python/examples/heartbeat.py create mode 100644 python/examples/here-now.py create mode 100644 python/examples/history.py create mode 100644 python/examples/pam_demo/demo.py create mode 100644 python/examples/presence.py create mode 100644 python/examples/publish.py create mode 100644 python/examples/pubnub-console/pubnub-console create mode 100644 python/examples/pubnub-console/setup.py create mode 100644 python/examples/requirements.pip create mode 100644 python/examples/revoke.py create mode 100644 python/examples/start-console.sh create mode 100644 python/examples/state.py create mode 100644 python/examples/subscribe.py create mode 100644 python/examples/subscribe_group.py create mode 100644 python/examples/where-now.py create mode 100644 python/examples/wildcard_subscribe.py create mode 100644 python/migration.md create mode 100644 python/tests/test_cg.py create mode 100644 python/tests/test_grant.py create mode 100644 python/tests/test_history.py create mode 100644 python/tests/test_wildcard.py diff --git a/python-tornado/LICENSE b/python-tornado/LICENSE new file mode 100644 index 0000000..3efa392 --- /dev/null +++ b/python-tornado/LICENSE @@ -0,0 +1,27 @@ +PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks +Copyright (c) 2013 PubNub Inc. +http://www.pubnub.com/ +http://www.pubnub.com/terms + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks +Copyright (c) 2013 PubNub Inc. +http://www.pubnub.com/ +http://www.pubnub.com/terms diff --git a/python-tornado/README.md b/python-tornado/README.md new file mode 100644 index 0000000..eaa2fe0 --- /dev/null +++ b/python-tornado/README.md @@ -0,0 +1,137 @@ +## Contact support@pubnub.com for all questions + +#### [PubNub](http://www.pubnub.com) Real-time Data Network +##### Tornado Client + +## IO Event Loop +Be sure to eventually start the event loop or PubNub won't run! + +``` +pubnub.start() +``` + +#### Import +``` +from pubnub import PubnubTornado as Pubnub +``` + +#### Init +``` +pubnub = Pubnub(publish_key="demo", subscribe_key="demo", ssl_on=False) +``` + +#### Publish Example +``` +channel = 'hello_world' +message = 'Hello World !!!' + +# Asynchronous usage + + +def callback(message): + print(message) + +pubnub.publish(channel, message, callback=callback, error=callback) +``` + +#### Subscribe Example +``` +channel = 'hello_world' + +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) +``` + +#### History Example +``` +def callback(message): + print(message) + +pubnub.history(channel, count=2, callback=callback, error=callback) +``` + +#### Here Now Example +``` +def callback(message): + print(message) + +pubnub.here_now(channel, callback=callback, error=callback) +``` + +#### Presence Example +``` +channel = 'hello_world' + +def callback(message, channel): + print(message) + + +def error(message): + print("ERROR : " + str(message)) + +pubnub.presence(channel, callback=callback, error=callback) +``` + +#### Unsubscribe Example +``` +pubnub.unsubscribe(channel='hello_world') +``` + +#### Grant Example +``` +authkey = "abcd" + +def callback(message): + print(message) + +pubnub.grant(channel, authkey, True, True, callback=callback, error=callback) + +``` + +#### Audit Example +``` +authkey = "abcd" + +def callback(message): + print(message) + +pubnub.audit(channel, authkey, callback=callback, error=callback) +``` + +#### Revoke Example +``` +authkey = "abcd" + +def callback(message): + print(message) + +pubnub.revoke(channel, authkey, callback=callback, error=callback) +``` + + +#### IO Event Loop start +``` +pubnub.start() +``` + +## Contact support@pubnub.com for all questions diff --git a/python-tornado/examples/audit.py b/python-tornado/examples/audit.py new file mode 100644 index 0000000..2e7fa5b --- /dev/null +++ b/python-tornado/examples/audit.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 PubnubTornado as Pubnub + +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'pam' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'pam' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'pam' +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' +authkey = "abcd" + + +def callback(message): + print(message) + pubnub.stop() + + +pubnub.audit(channel, auth_key=authkey, callback=callback, error=callback) + +pubnub.start() diff --git a/python-tornado/examples/grant.py b/python-tornado/examples/grant.py new file mode 100644 index 0000000..52c7acd --- /dev/null +++ b/python-tornado/examples/grant.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 PubnubTornado as Pubnub + +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'pam' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'pam' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'pam' +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' +authkey = "abcd" + + +def callback(message): + print(message) + pubnub.stop() + + +pubnub.grant(channel, authkey, True, True, callback=callback, error=callback) + +pubnub.start() diff --git a/python-tornado/examples/here-now.py b/python-tornado/examples/here-now.py new file mode 100644 index 0000000..9d3e028 --- /dev/null +++ b/python-tornado/examples/here-now.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 PubnubTornado as 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' + + +# Asynchronous usage + +def callback(message): + print(message) + pubnub.stop() + + +pubnub.here_now(channel, callback=callback, error=callback) + +pubnub.start() diff --git a/python-tornado/examples/history.py b/python-tornado/examples/history.py new file mode 100644 index 0000000..3c7bbe4 --- /dev/null +++ b/python-tornado/examples/history.py @@ -0,0 +1,37 @@ +# 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 PubnubTornado as 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): + print(message) + pubnub.stop() + + +pubnub.history(channel, count=2, callback=callback, error=callback) + +pubnub.start() diff --git a/python-tornado/examples/presence_group.py b/python-tornado/examples/presence_group.py new file mode 100644 index 0000000..2384b50 --- /dev/null +++ b/python-tornado/examples/presence_group.py @@ -0,0 +1,67 @@ +# 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 PubnubTornado as 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 'abcd' +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 = 'ab' + + +# Asynchronous usage + +def callback_abc(message, channel, real_channel): + print(str(message) + ' , ' + channel + ', ' + real_channel) + # pubnub.unsubscribe_group(channel_group='abc') + # pubnub.stop() + + +def callback_d(message, channel): + print(str(message) + ' , ' + channel) + + +def error(message): + print("ERROR : " + str(message)) + + +def connect_abc(message): + print("CONNECTED " + str(message)) + + +def connect_d(message): + print("CONNECTED " + str(message)) + pubnub.unsubscribe(channel='d') + + +def reconnect(message): + print("RECONNECTED " + str(message)) + + +def disconnect(message): + print("DISCONNECTED " + str(message)) + + +print(pubnub.channel_group_add_channel(channel_group='abc', channel="bn")) + +pubnub.presence_group(channel_group='abc', callback=callback_abc, error=error) + +pubnub.presence(channel='d', callback=callback_d, error=error) + +pubnub.start() diff --git a/python-tornado/examples/publish.py b/python-tornado/examples/publish.py new file mode 100644 index 0000000..5cc8757 --- /dev/null +++ b/python-tornado/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 PubnubTornado as 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 !!!' + + +# Asynchronous usage +def callback(message): + print(message) + pubnub.stop() + + +pubnub.publish(channel, message, callback=callback, error=callback) + +pubnub.start() diff --git a/python-tornado/examples/revoke.py b/python-tornado/examples/revoke.py new file mode 100644 index 0000000..1231782 --- /dev/null +++ b/python-tornado/examples/revoke.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 PubnubTornado as Pubnub + +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'pam' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'pam' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'pam' +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' +authkey = "abcd" + + +def callback(message): + print(message) + pubnub.stop() + + +pubnub.revoke(channel, authkey, callback=callback, error=callback) + +pubnub.start() diff --git a/python-tornado/examples/subscribe.py b/python-tornado/examples/subscribe.py new file mode 100644 index 0000000..597db11 --- /dev/null +++ b/python-tornado/examples/subscribe.py @@ -0,0 +1,52 @@ +# 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 PubnubTornado as 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) + +pubnub.start() diff --git a/python-tornado/examples/subscribe_group.py b/python-tornado/examples/subscribe_group.py new file mode 100644 index 0000000..4f92353 --- /dev/null +++ b/python-tornado/examples/subscribe_group.py @@ -0,0 +1,69 @@ +# 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 PubnubTornado as 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 'abcd' +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 = 'ab' + + +# Asynchronous usage + +def callback_abc(message, channel, real_channel): + print(str(message) + ' , ' + channel + ', ' + real_channel) + pubnub.unsubscribe_group(channel_group='abc') + pubnub.stop() + + +def callback_d(message, channel): + print(str(message) + ' , ' + channel) + + +def error(message): + print("ERROR : " + str(message)) + + +def connect_abc(message): + print("CONNECTED " + str(message)) + + +def connect_d(message): + print("CONNECTED " + str(message)) + pubnub.unsubscribe(channel='d') + + +def reconnect(message): + print("RECONNECTED " + str(message)) + + +def disconnect(message): + print("DISCONNECTED " + str(message)) + + +print(pubnub.channel_group_add_channel(channel_group='abc', channel="b")) + +pubnub.subscribe_group(channel_groups='abc', callback=callback_abc, error=error, + connect=connect_abc, reconnect=reconnect, disconnect=disconnect) + +pubnub.subscribe(channels='d', callback=callback_d, error=error, + connect=connect_d, reconnect=reconnect, disconnect=disconnect) + +pubnub.start() diff --git a/python-tornado/migration.md b/python-tornado/migration.md new file mode 100644 index 0000000..6a1abf3 --- /dev/null +++ b/python-tornado/migration.md @@ -0,0 +1,205 @@ +## Contact support@pubnub.com for all questions + +#### [PubNub](http://www.pubnub.com) Real-time Data Network +##### Tornado Migration + +#### Import + +``` +# Pre 3.5: +from pubnub import Pubnub + +# New in 3.5+ +from pubnub import PubnubTornado as Pubnub + +``` + + +#### 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: +def callback(messages): + print(messages) + +pubnub.publish( { + 'channel' : channel, + 'message' : message, + 'callback' : callback +}) + +# New in 3.5+ + +def callback(message): + print(message) + +pubnub.publish(channel, message, callback=callback, error=callback) + +``` + + +#### SUBSCRIBE + +``` + +# Listen for Messages + +channel = 'hello_world' + +# Pre 3.5: +def connected() : + print('CONNECTED') + +def message_received(message): + print(message) + +pubnub.subscribe({ + 'channel' : channel, + 'connect' : connected, + 'callback' : message_received +}) + +# 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: +pubnub.unsubscribe({ + 'channel' : 'hello_world' +}) + +# New in 3.5+ + +pubnub.unsubscribe(channel='hello_world') +``` + +#### PRESENCE + +``` + +# Pre 3.5: +# + +# New in 3.5+ + +# Listen for Presence Event Messages + +channel = 'hello_world' + +def callback(message, channel): + print(message) + + +def error(message): + print("ERROR : " + str(message)) + +pubnub.presence(channel, callback=callback, error=callback) +``` + +#### HERE_NOW + +``` + +channel = 'hello_world' + +# Pre 3.5: +def callback(messages): + print(messages) + +pubnub.here_now( { + 'channel' : channel, + 'callback' : callback +}) + + +# New in 3.5+ + +# Get info on who is here right now! + + +def callback(message): + print(message) + +pubnub.here_now(channel, callback=callback, error=callback) +``` + +#### HISTORY + +``` +channel = 'hello_world' + +# Pre 3.5: +def history_complete(messages): + print(messages) + +pubnub.history( { + 'channel' : channel, + 'limit' : 2, + 'callback' : history_complete +}) + + +# New in 3.5+ + +def callback(message): + print(message) + +pubnub.history(channel, count=2, callback=callback, error=callback) +``` + +#### IO Event Loop + +``` + +# Pre 3.5: +tornado.ioloop.IOLoop.instance().start() + +# New in 3.5+ +pubnub.start() +``` +## Contact support@pubnub.com for all questions diff --git a/python-tornado/tests/test_grant_async.py b/python-tornado/tests/test_grant_async.py new file mode 100644 index 0000000..bb6121c --- /dev/null +++ b/python-tornado/tests/test_grant_async.py @@ -0,0 +1,354 @@ +import time + +from pubnub import PubnubTornado as Pubnub + +subkey = "sub-c-9aeec0d4-cdf4-11e5-bcee-0619f8945a4f" +pubkey = "pub-c-b3fdf8fc-4516-4ab2-8836-6fb22ba7870d" +secretkey = "sec-c-ZDQwNTUwMDctZDViYi00MzhlLTg2NTctYjViZDcwNTA5Zjhj" +pubnub = Pubnub(pubkey, subkey) +pubnub_pam = Pubnub(pubkey, subkey, secretkey) + + +# Grant permission read true, write true, on channel ( Async Mode ) +def test_1(): + def _callback(resp, ch=None): + assert resp == { + 'message': 'Success', + 'payload': {'auths': {'abcd': {'r': 1, 'w': 1, 'm': 0}}, + 'subscribe_key': subkey, + 'level': 'user', 'channel': 'abcd', 'ttl': 1} + } + + def _error(response): + assert False + + pubnub_pam.grant(channel="abcd", auth_key="abcd", read=True, write=True, ttl=1, callback=_callback, error=_error) + + +# Grant permission read false, write false, on channel ( Async Mode ) +def test_2(): + def _callback(resp, ch=None): + assert resp == { + 'message': 'Success', + 'payload': {'auths': {'abcd': {'r': 0, 'w': 0, 'm': 0}}, + 'subscribe_key': subkey, + 'level': 'user', 'channel': 'abcd', 'ttl': 1} + } + + def _error(response): + print("error") + print(response) + assert False + + pubnub_pam.grant(channel="abcd", auth_key="abcd", read=False, write=False, ttl=1, callback=_callback, error=_error) + + +# Grant permission read True, write false, on channel ( Async Mode ) +def test_3(): + def _callback(resp, ch=None): + assert resp == { + 'message': 'Success', + 'payload': {'auths': {'abcd': {'r': 1, 'w': 0, 'm': 0}}, + 'subscribe_key': subkey, + 'level': 'user', 'channel': 'abcd', 'ttl': 1} + } + + def _error(response): + assert False + + pubnub_pam.grant(channel="abcd", auth_key="abcd", read=True, write=False, ttl=1, callback=_callback, error=_error) + + +# Grant permission read False, write True, on channel ( Async Mode ) +def test_4(): + def _callback(resp, ch=None): + assert resp == { + 'message': 'Success', + 'payload': {'auths': {'abcd': {'r': 0, 'w': 1, 'm': 0}}, + 'subscribe_key': subkey, + 'level': 'user', 'channel': 'abcd', 'ttl': 1} + } + + def _error(response): + assert False + + pubnub_pam.grant(channel="abcd", auth_key="abcd", read=False, write=True, ttl=1, callback=_callback, error=_error) + + +# Grant permission read False, write True, on channel ( Async Mode ), TTL 10 +def test_5(): + def _callback(resp, ch=None): + assert resp == { + 'message': 'Success', + 'payload': {'auths': {'abcd': {'r': 0, 'w': 1, 'm': 0}}, + 'subscribe_key': subkey, + 'level': 'user', 'channel': 'abcd', 'ttl': 10} + } + + def _error(response): + assert False + + pubnub_pam.grant(channel="abcd", auth_key="abcd", read=False, write=True, ttl=10, callback=_callback, error=_error) + + +# Grant permission read False, write True, without channel ( Async Mode ), TTL 10 +def test_6(): + def _callback(resp, ch=None): + assert resp == { + 'message': 'Success', + 'payload': {'r': 0, 'w': 1, 'm': 0, + 'subscribe_key': subkey, + 'level': 'subkey', 'ttl': 10} + } + + def _error(response): + print(response) + assert False + + pubnub_pam.grant(read=False, write=True, ttl=10, callback=_callback, error=_error) + + +# Grant permission read False, write False, without channel ( Async Mode ) +def test_7(): + def _callback(resp, ch=None): + assert resp == { + 'message': 'Success', + 'payload': {'r': 0, 'w': 0, 'm': 0, + 'subscribe_key': subkey, + 'level': 'subkey', 'ttl': 1} + } + + def _error(response): + assert False + + pubnub_pam.grant(read=False, write=False, callback=_callback, error=_error) + + +# 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.set_auth_key(auth_key) + + def _cb2(resp): + assert resp == { + 'message': 'Success', + 'payload': {'auths': {auth_key: {'r': 1, 'w': 1, 'm': 0}}, + 'subscribe_key': subkey, + 'level': 'user', 'channel': channel, 'ttl': 10} + } + + def _cb3(resp, ch=None): + assert resp[0] == 1 + + def _err3(resp): + print(resp) + assert False + + time.sleep(7) + pubnub.publish(channel=channel, message=message, callback=_cb3, error=_err3) + + def _err2(): + assert False + + pubnub_pam.grant(channel=channel, read=True, write=True, auth_key=auth_key, ttl=10, callback=_cb2, error=_err2) + + +# 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.set_auth_key(auth_key) + + def _cb2(resp): + assert resp == { + 'message': 'Success', + 'payload': {'auths': {auth_key: {'r': 1, 'w': 1, 'm': 0}}, + 'subscribe_key': subkey, + 'level': 'user', 'channel': channel, 'ttl': 10} + } + + def _cb3(resp, ch=None): + assert resp[0] == 1 + + def _cb4(resp, ch=None): + assert resp == { + 'message': 'Success', + 'payload': {'auths': {auth_key: {'r': 0, 'w': 0, 'm': 0}}, + 'subscribe_key': subkey, + 'level': 'user', 'channel': channel, 'ttl': 1} + } + + def _cb5(resp, ch=None): + print(resp) + assert False + + def _err5(resp): + assert resp['message'] == 'Forbidden' + assert resp['payload'] == {'channels': [channel]} + + time.sleep(5) + pubnub.publish(channel=channel, message=message, callback=_cb5, error=_err5) + + def _err4(resp): + assert False + + pubnub_pam.revoke(channel=channel, auth_key=auth_key, callback=_cb4, error=_err4) + + def _err3(resp): + assert False + + time.sleep(7) + pubnub.publish(channel=channel, message=message, callback=_cb3, error=_err3) + + def _err2(resp): + assert False + + pubnub_pam.grant(channel=channel, read=True, write=True, auth_key=auth_key, ttl=10, callback=_cb2, error=_err2) + + +# 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 _cb2(resp, ch=None): + assert resp == { + 'message': 'Success', + 'payload': {'channels': {channel: {'r': 1, 'w': 1, 'm': 0}}, + 'subscribe_key': subkey, + 'level': 'channel', 'ttl': 10} + } + + def _cb3(resp, ch=None): + assert resp[0] == 1 + + def _cb4(resp, ch=None): + assert resp == { + 'message': 'Success', + 'payload': {'channels': {channel: {'r': 0, 'w': 0, 'm': 0}}, + 'subscribe_key': subkey, + 'level': 'channel', 'ttl': 1} + } + + def _cb5(resp, ch=None): + assert False + + def _err5(resp): + assert resp['message'] == 'Forbidden' + assert resp['payload'] == {'channels': [channel]} + + time.sleep(5) + pubnub.publish(channel=channel, message=message, callback=_cb5, error=_err5) + + def _err4(resp): + assert False + + pubnub_pam.revoke(channel=channel, callback=_cb4, error=_err4) + + def _err3(resp): + assert False + + time.sleep(5) + pubnub.publish(channel=channel, message=message, callback=_cb3, error=_err3) + + def _err2(resp): + assert False + + pubnub_pam.grant(channel=channel, read=True, write=True, ttl=10, callback=_cb2, error=_err2) + + +# 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.set_auth_key(auth_key) + + def _cb2(resp, ch=None): + assert resp == { + 'message': 'Success', + 'payload': {'r': 1, 'w': 1, 'm': 0, + 'subscribe_key': subkey, + 'level': 'subkey', 'ttl': 10} + } + + def _cb3(resp, ch=None): + assert resp[0] == 1 + + def _cb4(resp, ch=None): + assert resp == { + 'message': 'Success', + 'payload': {'r': 0, 'w': 0, 'm': 0, + 'subscribe_key': subkey, + 'level': 'subkey', 'ttl': 1} + } + + def _cb5(resp, ch=None): + assert False + + def _err5(resp): + assert resp['message'] == 'Forbidden' + assert resp['payload'] == {'channels': [channel]} + + time.sleep(5) + pubnub.publish(channel=channel, message=message, callback=_cb5, error=_err5) + + def _err4(resp): + assert False + + pubnub_pam.revoke(callback=_cb4, error=_err4) + + def _err3(resp): + assert False + + time.sleep(5) + pubnub.publish(channel=channel, message=message, callback=_cb3, error=_err3) + + def _err2(resp): + assert False + + pubnub_pam.grant(read=True, write=True, ttl=10, callback=_cb2, error=_err2) + + +x = 5 + + +def run_test(t): + global x + x += 5 + i = (x / 5) - 1 + + def _print(): + print('Running test ' + str(i)) + + pubnub.timeout(x, _print) + pubnub.timeout(x + 1, t) + + +def stop(): + pubnub.stop() + + +run_test(test_1) +run_test(test_2) +run_test(test_3) +run_test(test_4) +run_test(test_5) +run_test(test_6) +run_test(test_7) +run_test(test_8) +run_test(test_9) +run_test(test_10) +run_test(test_11) +run_test(stop) + +pubnub_pam.start() diff --git a/python-tornado/tests/test_publish_async.py b/python-tornado/tests/test_publish_async.py new file mode 100644 index 0000000..b8ddcdc --- /dev/null +++ b/python-tornado/tests/test_publish_async.py @@ -0,0 +1,333 @@ +import time +# from twisted.trial import unittest + +from pubnub import PubnubTornado as Pubnub + +pubkey = "pub-c-37d3c709-c35e-487a-8b33-2314d9b62b28" +subkey = "sub-c-cd0b6288-cdf5-11e5-bcee-0619f8945a4f" +pubnub = Pubnub(pubkey, subkey) +pubnub_enc = Pubnub(pubkey, subkey, cipher_key="enigma") + + +# class PublishTests(unittest.TestCase): +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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + print(resp) + assert False + + pubnub.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub_enc.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub_enc.publish(channel, message, callback=_cb1, error=_err1) + + def _error(resp): + assert False + + pubnub_enc.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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub_enc.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub_enc.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub_enc.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub_enc.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub_enc.publish(channel, message, callback=_cb1, error=_err1) + + def _error(resp): + assert False + + pubnub_enc.subscribe(channel, callback=_cb, connect=_connect, error=_error) + + +x = 5 + + +def run_test(t): + global x + x += 5 + i = (x / 5) - 1 + + def _print(): + print('Running test ' + str(i)) + + pubnub.timeout(x, _print) + pubnub.timeout(x + 1, t) + + +def stop(): + pubnub.stop() + + +run_test(test_1) +run_test(test_2) +run_test(test_3) +run_test(test_4) +run_test(test_5) +run_test(test_6) +run_test(test_7) +run_test(test_8) +run_test(test_9) +run_test(test_10) +run_test(test_11) +run_test(stop) + +pubnub_enc.start() diff --git a/python-twisted/LICENSE b/python-twisted/LICENSE new file mode 100644 index 0000000..3efa392 --- /dev/null +++ b/python-twisted/LICENSE @@ -0,0 +1,27 @@ +PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks +Copyright (c) 2013 PubNub Inc. +http://www.pubnub.com/ +http://www.pubnub.com/terms + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks +Copyright (c) 2013 PubNub Inc. +http://www.pubnub.com/ +http://www.pubnub.com/terms diff --git a/python-twisted/README.md b/python-twisted/README.md new file mode 100644 index 0000000..0677eff --- /dev/null +++ b/python-twisted/README.md @@ -0,0 +1,137 @@ +## Contact support@pubnub.com for all questions + +#### [PubNub](http://www.pubnub.com) Real-time Data Network +##### Twisted Client + +## IO Event Loop +Be sure to eventually start the event loop or PubNub won't run! + +``` +pubnub.start() +``` + +#### Import +``` +from pubnub import PubnubTwisted as Pubnub +``` + +#### Init +``` +pubnub = Pubnub(publish_key="demo", subscribe_key="demo", ssl_on=False) +``` + +#### Publish Example +``` +channel = 'hello_world' +message = 'Hello World !!!' + +# Asynchronous usage + + +def callback(message): + print(message) + +pubnub.publish(channel, message, callback=callback, error=callback) +``` + +#### Subscribe Example +``` +channel = 'hello_world' + +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) +``` + +#### History Example +``` +def callback(message): + print(message) + +pubnub.history(channel, count=2, callback=callback, error=callback) +``` + +#### Here Now Example +``` +def callback(message): + print(message) + +pubnub.here_now(channel, callback=callback, error=callback) +``` + +#### Presence Example +``` +channel = 'hello_world' + +def callback(message, channel): + print(message) + + +def error(message): + print("ERROR : " + str(message)) + +pubnub.presence(channel, callback=callback, error=callback) +``` + +#### Unsubscribe Example +``` +pubnub.unsubscribe(channel='hello_world') +``` + +#### Grant Example +``` +authkey = "abcd" + +def callback(message): + print(message) + +pubnub.grant(channel, authkey, True, True, callback=callback, error=callback) + +``` + +#### Audit Example +``` +authkey = "abcd" + +def callback(message): + print(message) + +pubnub.audit(channel, authkey, callback=callback, error=callback) +``` + +#### Revoke Example +``` +authkey = "abcd" + +def callback(message): + print(message) + +pubnub.revoke(channel, authkey, callback=callback, error=callback) +``` + + +#### IO Event Loop start +``` +pubnub.start() +``` + +## Contact support@pubnub.com for all questions diff --git a/python-twisted/examples/audit.py b/python-twisted/examples/audit.py new file mode 100644 index 0000000..2f2b08a --- /dev/null +++ b/python-twisted/examples/audit.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 PubnubTwisted as Pubnub + +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'pam' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'pam' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'pam' +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' +authkey = "abcd" + + +def callback(message): + print(message) + pubnub.stop() + + +pubnub.audit(channel, auth_key=authkey, callback=callback, error=callback) + +pubnub.start() diff --git a/python-twisted/examples/echo-client.py b/python-twisted/examples/echo-client.py new file mode 100644 index 0000000..510fee1 --- /dev/null +++ b/python-twisted/examples/echo-client.py @@ -0,0 +1,99 @@ +# www.pubnub.com - PubNub - Data Stream Network +# coding=utf8 + +# PubNub Real-time Push APIs and Notifications Framework +# Copyright (c) 2010 Stephen Blum +# http://www.pubnub.com/ + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Import Libs +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +from pubnub import PubnubTwisted as Pubnub + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Configuration +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +publish_key = 'pub-c-f6a20151-db8d-45af-ba42-def0edaa459f' +subscribe_key = 'sub-c-b5ff3208-7f64-11e4-b601-02ee2ddab7fe' +server_channel = 'echo-server' +client_channel = 'echo-channel' + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Create PubNub Instance +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +pubnub = Pubnub( + publish_key=publish_key, + subscribe_key=subscribe_key, + ssl_on=True +) + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Error Log +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +def error_log(data): + print(data) + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Access Log +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +def access_log(data): + print(data) + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Respond +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +def request(): + pubnub.publish( + server_channel, + {'response': client_channel, 'body': "Hello"}, + callback=access_log, + error=error_log + ) + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Request Received +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +def onResponse(data, channel): + print("Channel: %s | Req: %s" % (channel, data)) + request() + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Ready to Receive Requests +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +def onReady(message): + print("Ready to Receive Requests on '%s'" % server_channel) + request() + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Network Recovered +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +def onReconnect(message): + print("RECONNECTED") + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Network Failed +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +def onDisconnect(message): + print("DISCONNECTED") + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Start Echo Server +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +pubnub.subscribe( + client_channel, + callback=onResponse, + error=error_log, + connect=onReady, + reconnect=onReconnect, + disconnect=onDisconnect +) + +pubnub.start() diff --git a/python-twisted/examples/echo-server.py b/python-twisted/examples/echo-server.py new file mode 100644 index 0000000..9485f4d --- /dev/null +++ b/python-twisted/examples/echo-server.py @@ -0,0 +1,104 @@ +# www.pubnub.com - PubNub - Data Stream Network +# coding=utf8 + +# PubNub Real-time Push APIs and Notifications Framework +# Copyright (c) 2010 Stephen Blum +# http://www.pubnub.com/ + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Import Libs +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +from pubnub import PubnubTwisted as Pubnub + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Configuration +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +publish_key = 'pub-c-f6a20151-db8d-45af-ba42-def0edaa459f' +subscribe_key = 'sub-c-b5ff3208-7f64-11e4-b601-02ee2ddab7fe' +server_channel = 'echo-server' + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Create PubNub Instance +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +pubnub = Pubnub( + publish_key=publish_key, + subscribe_key=subscribe_key, + ssl_on=True +) + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Error Log +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +def error_log(data): + print(data) + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Access Log +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +def access_log(data): + print(data) + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Respond +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +def respond(channel, body): + pubnub.publish( + channel, + body, + callback=access_log, + error=error_log + ) + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Request Received +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +def onRequest(request, channel): + response_channel = request['response'] + response_body = request['body'] + + print("Channel: %s | Req: %s" % (channel, request)) + + respond( + channel=response_channel, + body=response_body + ) + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Ready to Receive Requests +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +def onReady(message): + print("Ready to Receive Requests on '%s'" % server_channel) + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Network Recovered +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +def onReconnect(message): + print("RECONNECTED") + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Network Failed +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +def onDisconnect(message): + print("DISCONNECTED") + + +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +# Start Echo Server +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +pubnub.subscribe( + server_channel, + callback=onRequest, + error=error_log, + connect=onReady, + reconnect=onReconnect, + disconnect=onDisconnect +) + +pubnub.start() diff --git a/python-twisted/examples/grant.py b/python-twisted/examples/grant.py new file mode 100644 index 0000000..f300c35 --- /dev/null +++ b/python-twisted/examples/grant.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 PubnubTwisted as Pubnub + +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'pam' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'pam' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'pam' +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' +authkey = "abcd" + + +def callback(message): + print(message) + pubnub.stop() + + +pubnub.grant(channel, authkey, True, True, callback=callback, error=callback) + +pubnub.start() diff --git a/python-twisted/examples/here-now.py b/python-twisted/examples/here-now.py new file mode 100644 index 0000000..76a8ea8 --- /dev/null +++ b/python-twisted/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 PubnubTwisted as 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' + + +# Asynchronous usage +def callback(message): + print(message) + pubnub.stop() + + +pubnub.here_now(channel, callback=callback, error=callback) + +pubnub.start() diff --git a/python-twisted/examples/history.py b/python-twisted/examples/history.py new file mode 100644 index 0000000..12ce9d3 --- /dev/null +++ b/python-twisted/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 PubnubTwisted as 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): + print(message) + pubnub.stop() + + +pubnub.history(channel, count=2, callback=callback, error=callback) + +pubnub.start() diff --git a/python-twisted/examples/publish.py b/python-twisted/examples/publish.py new file mode 100644 index 0000000..e618a19 --- /dev/null +++ b/python-twisted/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 PubnubTwisted as 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 !!!' + + +# Asynchronous usage +def callback(message): + print(message) + pubnub.stop() + + +pubnub.publish(channel, message, callback=callback, error=callback) + +pubnub.start() diff --git a/python-twisted/examples/revoke.py b/python-twisted/examples/revoke.py new file mode 100644 index 0000000..e800856 --- /dev/null +++ b/python-twisted/examples/revoke.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 PubnubTwisted as Pubnub + +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'pam' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'pam' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'pam' +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' +authkey = "abcd" + + +def callback(message): + print(message) + pubnub.stop() + + +pubnub.revoke(channel, authkey, callback=callback, error=callback) + +pubnub.start() diff --git a/python-twisted/examples/subscribe.py b/python-twisted/examples/subscribe.py new file mode 100644 index 0000000..d5b9b77 --- /dev/null +++ b/python-twisted/examples/subscribe.py @@ -0,0 +1,52 @@ +# 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 PubnubTwisted as 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) + +pubnub.start() diff --git a/python-twisted/examples/subscribe_group.py b/python-twisted/examples/subscribe_group.py new file mode 100644 index 0000000..f3909e5 --- /dev/null +++ b/python-twisted/examples/subscribe_group.py @@ -0,0 +1,54 @@ +# 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 'abcd' +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, daemon=False) + +channel = 'ab' + + +# Asynchronous usage +def callback(message, channel): + print(str(message) + ' , ' + channel) + + +def error(message): + print("ERROR : " + str(message)) + + +def connect(message): + print("CONNECTED " + str(message)) + + +def reconnect(message): + print("RECONNECTED " + str(message)) + + +def disconnect(message): + print("DISCONNECTED " + str(message)) + + +print(pubnub.channel_group_add_channel(channel_group='abc', channel="a")) + +pubnub.subscribe_group(channel_groups='abc', callback=callback, error=callback, + connect=connect, reconnect=reconnect, disconnect=disconnect) + +pubnub.start() diff --git a/python-twisted/migration.md b/python-twisted/migration.md new file mode 100644 index 0000000..924fa7c --- /dev/null +++ b/python-twisted/migration.md @@ -0,0 +1,205 @@ +## Contact support@pubnub.com for all questions + +#### [PubNub](http://www.pubnub.com) Real-time Data Network +##### Twisted Migration + +#### Import + +``` +# Pre 3.5: +from pubnub import Pubnub + +# New in 3.5+ +from pubnub import PubnubTwisted as Pubnub + +``` + + +#### 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: +def callback(messages): + print(messages) + +pubnub.publish( { + 'channel' : channel, + 'message' : message, + 'callback' : callback +}) + +# New in 3.5+ + +def callback(message): + print(message) + +pubnub.publish(channel, message, callback=callback, error=callback) + +``` + + +#### SUBSCRIBE + +``` + +# Listen for Messages + +channel = 'hello_world' + +# Pre 3.5: +def connected() : + print('CONNECTED') + +def message_received(message): + print(message) + +pubnub.subscribe({ + 'channel' : channel, + 'connect' : connected, + 'callback' : message_received +}) + +# 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: +pubnub.unsubscribe({ + 'channel' : 'hello_world' +}) + +# New in 3.5+ + +pubnub.unsubscribe(channel='hello_world') +``` + +#### PRESENCE + +``` + +# Pre 3.5: +# + +# New in 3.5+ + +# Listen for Presence Event Messages + +channel = 'hello_world' + +def callback(message, channel): + print(message) + + +def error(message): + print("ERROR : " + str(message)) + +pubnub.presence(channel, callback=callback, error=callback) +``` + +#### HERE_NOW + +``` + +channel = 'hello_world' + +# Pre 3.5: +def callback(messages): + print(messages) + +pubnub.here_now( { + 'channel' : channel, + 'callback' : callback +}) + + +# New in 3.5+ + +# Get info on who is here right now! + + +def callback(message): + print(message) + +pubnub.here_now(channel, callback=callback, error=callback) +``` + +#### HISTORY + +``` +channel = 'hello_world' + +# Pre 3.5: +def history_complete(messages): + print(messages) + +pubnub.history( { + 'channel' : channel, + 'limit' : 2, + 'callback' : history_complete +}) + + +# New in 3.5+ + +def callback(message): + print(message) + +pubnub.history(channel, count=2, callback=callback, error=callback) +``` + +#### IO Event Loop + +``` + +# Pre 3.5: +reactor.run() + +# New in 3.5+ +pubnub.start() +``` +## Contact support@pubnub.com for all questions diff --git a/python-twisted/tests/benchmark.py b/python-twisted/tests/benchmark.py new file mode 100644 index 0000000..a715d66 --- /dev/null +++ b/python-twisted/tests/benchmark.py @@ -0,0 +1,90 @@ +# 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 datetime +import sys + +from pubnub import PubnubTwisted as Pubnub + +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' +cipher_key = len(sys.argv) > 4 and sys.argv[4] or 'demo' +ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False +origin = len(sys.argv) > 6 and sys.argv[6] or 'pubsub.pubnub.com' + +# ----------------------------------------------------------------------- +# Initiat Class +# ----------------------------------------------------------------------- +pubnub = Pubnub( + publish_key, + subscribe_key, + secret_key=secret_key, + cipher_key=cipher_key, + ssl_on=ssl_on, + origin=origin +) +crazy = ' ~`!@#$%^&*( 顶顅 Ȓ)+=[]\\{}|;\':",./<>?abcd' + + +# ----------------------------------------------------------------------- +# BENCHMARK +# ----------------------------------------------------------------------- +def success(msg): + print(msg) + + +def connected(msg): + pubnub.publish(crazy, {'Info': 'Connected!'}, error=error, callback=success) + + +def error(err): + print(err) + +trips = {'last': None, 'current': None, 'max': 0, 'avg': 0} + + +def received(message): + current_trip = trips['current'] = str(datetime.datetime.now())[0:19] + last_trip = trips['last'] = str( + datetime.datetime.now() - datetime.timedelta(seconds=1) + )[0:19] + + # New Trip Span (1 Second) + if current_trip not in trips: + trips[current_trip] = 0 + + # Average + if last_trip in trips: + trips['avg'] = (trips['avg'] + trips[last_trip]) / 2 + + # Increment Trip Counter + trips[current_trip] = trips[current_trip] + 1 + + # Update Max + if trips[current_trip] > trips['max']: + trips['max'] = trips[current_trip] + + print(message) + + pubnub.publish(crazy, current_trip + + " Trip: " + + str(trips[current_trip]) + + " MAX: " + + str(trips['max']) + + "/sec " + + " AVG: " + + str(trips['avg']) + + "/sec", error=error) + + +pubnub.subscribe(crazy, received, connect=connected, error=error) + +# ----------------------------------------------------------------------- +# IO Event Loop +# ----------------------------------------------------------------------- +pubnub.start() diff --git a/python-twisted/tests/delivery.py b/python-twisted/tests/delivery.py new file mode 100644 index 0000000..457c6a9 --- /dev/null +++ b/python-twisted/tests/delivery.py @@ -0,0 +1,168 @@ +## www.pubnub.com - PubNub Real-time push service in the cloud. +# coding=utf8 + +## PubNub Real-time Push APIs and Notifications Framework +## Copyright (c) 2010 Stephen Blum +## http://www.pubnub.com/ + +## ----------------------------------- +## PubNub 3.1 Real-time Push Cloud API +## ----------------------------------- + +import sys +import datetime +import time + +from pubnub import PubnubTwisted as Pubnub + +## ----------------------------------------------------------------------- +## Configuration +## ----------------------------------------------------------------------- +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' +cipher_key = len(sys.argv) > 4 and sys.argv[4] or 'demo' +ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False +origin = len(sys.argv) > 6 and sys.argv[6] or 'pubsub.pubnub.com' +origin = '184.72.9.220' + +## ----------------------------------------------------------------------- +## Analytics +## ----------------------------------------------------------------------- +analytics = { + 'publishes': 0, # Total Send Requests + 'received': 0, # Total Received Messages (Deliveries) + 'queued': 0, # Total Unreceived Queue (UnDeliveries) + 'successful_publishes': 0, # Confirmed Successful Publish Request + 'failed_publishes': 0, # Confirmed UNSuccessful Publish Request + 'failed_deliveries': 0, # (successful_publishes - received) + 'deliverability': 0 # Percentage Delivery +} + +trips = { + 'last': None, + 'current': None, + 'max': 0, + 'avg': 0 +} + +## ----------------------------------------------------------------------- +## Initiat Class +## ----------------------------------------------------------------------- +channel = 'deliverability-' + str(time.time()) +pubnub = Pubnub( + publish_key, + subscribe_key, + secret_key=secret_key, + cipher_key=cipher_key, + ssl_on=ssl_on, + origin=origin +) + +## ----------------------------------------------------------------------- +## BENCHMARK +## ----------------------------------------------------------------------- + + +def publish_sent(info=None): + if info and info[0]: + analytics['successful_publishes'] += 1 + else: + analytics['failed_publishes'] += 1 + + analytics['publishes'] += 1 + analytics['queued'] += 1 + + pubnub.timeout(send, 0.1) + + +def send(): + if analytics['queued'] > 100: + analytics['queued'] -= 10 + return pubnub.timeout(send, 10) + + pubnub.publish({ + 'channel': channel, + 'callback': publish_sent, + 'message': "1234567890" + }) + + +def received(message): + analytics['queued'] -= 1 + analytics['received'] += 1 + current_trip = trips['current'] = str(datetime.datetime.now())[0:19] + last_trip = trips['last'] = str( + datetime.datetime.now() - datetime.timedelta(seconds=1) + )[0:19] + + ## New Trip Span (1 Second) + if current_trip not in trips: + trips[current_trip] = 0 + + ## Average + if last_trip in trips: + trips['avg'] = (trips['avg'] + trips[last_trip]) / 2 + + ## Increment Trip Counter + trips[current_trip] = trips[current_trip] + 1 + + ## Update Max + if trips[current_trip] > trips['max']: + trips['max'] = trips[current_trip] + + +def show_status(): + ## Update Failed Deliveries + analytics['failed_deliveries'] = \ + analytics['successful_publishes'] \ + - analytics['received'] + + ## Update Deliverability + analytics['deliverability'] = ( + float(analytics['received']) / + float(analytics['successful_publishes'] or 1.0) + ) * 100.0 + + ## Print Display + print(( + "max:%(max)03d/sec " + + "avg:%(avg)03d/sec " + + "pubs:%(publishes)05d " + + "received:%(received)05d " + + "spub:%(successful_publishes)05d " + + "fpub:%(failed_publishes)05d " + + "failed:%(failed_deliveries)05d " + + "queued:%(queued)03d " + + "delivery:%(deliverability)03f%% " + + "" + ) % { + 'max': trips['max'], + 'avg': trips['avg'], + 'publishes': analytics['publishes'], + 'received': analytics['received'], + 'successful_publishes': analytics['successful_publishes'], + 'failed_publishes': analytics['failed_publishes'], + 'failed_deliveries': analytics['failed_deliveries'], + 'publishes': analytics['publishes'], + 'deliverability': analytics['deliverability'], + 'queued': analytics['queued'] + }) + pubnub.timeout(show_status, 1) + + +def connected(): + show_status() + pubnub.timeout(send, 1) + +print("Connected: %s\n" % origin) +pubnub.subscribe({ + 'channel': channel, + 'connect': connected, + 'callback': received +}) + +## ----------------------------------------------------------------------- +## IO Event Loop +## ----------------------------------------------------------------------- +pubnub.start() diff --git a/python-twisted/tests/subscribe-test.py b/python-twisted/tests/subscribe-test.py new file mode 100644 index 0000000..fd33ff7 --- /dev/null +++ b/python-twisted/tests/subscribe-test.py @@ -0,0 +1,156 @@ +## www.pubnub.com - PubNub Real-time push service in the cloud. +# coding=utf8 + +## PubNub Real-time Push APIs and Notifications Framework +## Copyright (c) 2010 Stephen Blum +## http://www.pubnub.com/ + +## ----------------------------------- +## PubNub 3.1 Real-time Push Cloud API +## ----------------------------------- + +import sys +from pubnub import PubnubTwisted 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 : ', threading.activeCount()) + print('errors = ', errors) + print(current_thread().getName(), ' , ', 'received = ', received) + + if received != message: + print('********** MISSED **************** ', 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 + }) + + +print(threading.activeCount()) + + +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-twisted/tests/test_grant_async.py b/python-twisted/tests/test_grant_async.py new file mode 100644 index 0000000..7fe66cb --- /dev/null +++ b/python-twisted/tests/test_grant_async.py @@ -0,0 +1,365 @@ +import time + +from pubnub import PubnubTwisted as Pubnub + +subkey = "sub-c-9aeec0d4-cdf4-11e5-bcee-0619f8945a4f" +pubkey = "pub-c-b3fdf8fc-4516-4ab2-8836-6fb22ba7870d" +secretkey = "sec-c-ZDQwNTUwMDctZDViYi00MzhlLTg2NTctYjViZDcwNTA5Zjhj" +pubnub = Pubnub(pubkey, subkey) +pubnub_pam = Pubnub(pubkey, subkey, secretkey) + + +# Grant permission read true, write true, on channel ( Async Mode ) +def test_1(): + def _callback(resp, ch=None): + assert resp == { + 'message': u'Success', + 'payload': {u'auths': {u'abcd': {u'r': 1, u'w': 1}}, + u'subscribe_key': subkey, + u'level': u'user', u'channel': u'abcd', u'ttl': 1} + } + + def _error(response): + assert False + + pubnub_pam.grant(channel="abcd", auth_key="abcd", read=True, write=True, ttl=1, callback=_callback, error=_error) + + +# Grant permission read false, write false, on channel ( Async Mode ) +def test_2(): + def _callback(resp, ch=None): + assert resp == { + 'message': u'Success', + 'payload': {u'auths': {u'abcd': {u'r': 0, u'm': 0, u'w': 0}}, + u'subscribe_key': subkey, + u'level': u'user', u'channel': u'abcd', u'ttl': 1} + } + + def _error(response): + print("error") + print(response) + assert False + + pubnub_pam.grant(channel="abcd", auth_key="abcd", read=False, write=False, ttl=1, callback=_callback, error=_error) + + +# Grant permission read True, write false, on channel ( Async Mode ) +def test_3(): + def _callback(resp, ch=None): + assert resp == { + 'message': u'Success', + 'payload': {u'auths': {u'abcd': {u'r': 1, u'm': 0, u'w': 0}}, + u'subscribe_key': subkey, + u'level': u'user', u'channel': u'abcd', u'ttl': 1} + } + + def _error(response): + assert False + + pubnub_pam.grant(channel="abcd", auth_key="abcd", read=True, write=False, ttl=1, callback=_callback, error=_error) + + +# Grant permission read False, write True, on channel ( Async Mode ) +def test_4(): + def _callback(resp, ch=None): + assert resp == { + 'message': u'Success', + 'payload': {u'auths': {u'abcd': {u'r': 0, u'm': 0, u'w': 1}}, + u'subscribe_key': subkey, + u'level': u'user', u'channel': u'abcd', u'ttl': 1} + } + + def _error(response): + assert False + + pubnub_pam.grant(channel="abcd", auth_key="abcd", read=False, write=True, ttl=1, callback=_callback, error=_error) + + +# Grant permission read False, write True, on channel ( Async Mode ), TTL 10 +def test_5(): + def _callback(resp, ch=None): + assert resp == { + 'message': u'Success', + 'payload': {u'auths': {u'abcd': {u'r': 0, u'm': 0, u'w': 1}}, + u'subscribe_key': subkey, + u'level': u'user', u'channel': u'abcd', u'ttl': 10} + } + + def _error(response): + assert False + + pubnub_pam.grant(channel="abcd", auth_key="abcd", read=False, write=True, ttl=10, callback=_callback, error=_error) + + +# Grant permission read False, write True, without channel ( Async Mode ), TTL 10 +def test_6(): + def _callback(resp, ch=None): + assert resp == { + 'message': u'Success', + 'payload': {u'r': 0, u'm': 0, u'w': 1, + u'subscribe_key': subkey, + u'level': u'subkey', u'ttl': 10} + } + + def _error(response): + print(response) + assert False + + pubnub_pam.grant(read=False, write=True, ttl=10, callback=_callback, error=_error) + + +# Grant permission read False, write False, without channel ( Async Mode ) +def test_7(): + def _callback(resp, ch=None): + assert resp == { + 'message': u'Success', + 'payload': {u'r': 0, u'm': 0, u'w': 0, + u'subscribe_key': subkey, + u'level': u'subkey', u'ttl': 1} + } + + def _error(response): + assert False + + pubnub_pam.grant(read=False, write=False, callback=_callback, error=_error) + + +# 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.set_auth_key(auth_key) + + def _cb2(resp, ch=None): + assert resp == { + 'message': u'Success', + 'payload': {u'auths': {auth_key: {u'r': 1, u'm': 0, u'w': 1}}, + u'subscribe_key': subkey, + u'level': u'user', u'channel': channel, u'ttl': 10} + } + + def _cb3(resp, ch=None): + assert resp[0] == 1 + + def _err3(resp): + print(resp) + assert False + + time.sleep(7) + pubnub.publish(channel=channel, message=message, callback=_cb3, error=_err3) + + def _err2(resp): + assert False + + pubnub_pam.grant(channel=channel, read=True, write=True, auth_key=auth_key, ttl=10, callback=_cb2, error=_err2) + + +# 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.set_auth_key(auth_key) + + def _cb2(resp, ch=None): + assert resp == { + 'message': u'Success', + 'payload': {u'auths': {auth_key: {u'r': 1, u'm': 0, u'w': 1}}, + u'subscribe_key': subkey, + u'level': u'user', u'channel': channel, u'ttl': 10} + } + + def _cb3(resp, ch=None): + assert resp[0] == 1 + + def _cb4(resp, ch=None): + assert resp == { + 'message': u'Success', + 'payload': {u'auths': {auth_key: {u'r': 0, u'm': 0, u'w': 0}}, + u'subscribe_key': subkey, + u'level': u'user', u'channel': channel, u'ttl': 1} + } + + def _cb5(resp, ch=None): + print(resp) + assert False + + def _err5(resp): + assert resp['message'] == 'Forbidden' + assert resp['payload'] == {u'channels': [channel]} + + time.sleep(5) + pubnub.publish(channel=channel, message=message, callback=_cb5, error=_err5) + + def _err4(resp): + assert False + + pubnub_pam.revoke(channel=channel, auth_key=auth_key, callback=_cb4, error=_err4) + + def _err3(resp): + assert False + + time.sleep(7) + pubnub.publish(channel=channel, message=message, callback=_cb3, error=_err3) + + def _err2(resp): + assert False + + pubnub_pam.grant(channel=channel, read=True, write=True, auth_key=auth_key, ttl=10, callback=_cb2, error=_err2) + + +# 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.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]} + + def _cb2(resp, ch=None): + assert resp == { + 'message': u'Success', + 'payload': {u'channels': {channel: {u'r': 1, u'm': 0, u'w': 1}}, + u'subscribe_key': subkey, + u'level': u'channel', u'ttl': 10} + } + + def _cb3(resp, ch=None): + assert resp[0] == 1 + + def _cb4(resp, ch=None): + assert resp == { + 'message': u'Success', + 'payload': {u'channels': {channel: {u'r': 0, u'm': 0, u'w': 0}}, + u'subscribe_key': subkey, + u'level': u'channel', u'ttl': 1} + } + + def _cb5(resp, ch=None): + print(resp) + assert False + + def _err5(resp): + assert resp['message'] == 'Forbidden' + assert resp['payload'] == {u'channels': [channel]} + + time.sleep(5) + pubnub.publish(channel=channel, message=message, callback=_cb5, error=_err5) + + def _err4(resp): + assert False + + pubnub_pam.revoke(channel=channel, callback=_cb4, error=_err4) + + def _err3(resp): + assert False + + time.sleep(5) + pubnub.publish(channel=channel, message=message, callback=_cb3, error=_err3) + + def _err2(resp): + assert False + + pubnub_pam.grant(channel=channel, read=True, write=True, ttl=10, callback=_cb2, error=_err2) + + pubnub.publish(channel=channel, message=message, callback=_cb1, error=_err1) + + +# 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.set_auth_key(auth_key) + + def _cb2(resp, ch=None): + print(resp) + assert resp == { + 'message': u'Success', + 'payload': {u'r': 1, u'm': 0, u'w': 1, + u'subscribe_key': subkey, + u'level': u'subkey', u'ttl': 10} + } + + def _cb3(resp, ch=None): + assert resp[0] == 1 + + def _cb4(resp, ch=None): + assert resp == { + 'message': u'Success', + 'payload': {u'r': 0, u'm': 0, u'w': 0, + u'subscribe_key': subkey, + u'level': u'subkey', u'ttl': 1} + } + + def _cb5(resp, ch=None): + assert False + + def _err5(resp): + assert resp['message'] == 'Forbidden' + assert resp['payload'] == {u'channels': [channel]} + + time.sleep(5) + pubnub.publish(channel=channel, message=message, callback=_cb5, error=_err5) + + def _err4(resp): + assert False + + pubnub_pam.revoke(callback=_cb4, error=_err4) + + def _err3(resp): + assert False + + time.sleep(5) + pubnub.publish(channel=channel, message=message, callback=_cb3, error=_err3) + + def _err2(resp): + assert False + + pubnub_pam.grant(read=True, write=True, ttl=10, callback=_cb2, error=_err2) + + +x = 5 + + +def run_test(t): + global x + x += 5 + i = (x / 5) - 1 + + def _print(): + print('Running test ' + str(i)) + + pubnub.timeout(x, _print) + pubnub.timeout(x + 1, t) + + +def stop(): + pubnub.stop() + + +run_test(test_1) +run_test(test_2) +run_test(test_3) +run_test(test_4) +run_test(test_5) +run_test(test_6) +run_test(test_7) +run_test(test_8) +run_test(test_9) +run_test(test_10) +run_test(test_11) +run_test(stop) + +pubnub_pam.start() diff --git a/python-twisted/tests/test_publish_async.py b/python-twisted/tests/test_publish_async.py new file mode 100644 index 0000000..a188cfb --- /dev/null +++ b/python-twisted/tests/test_publish_async.py @@ -0,0 +1,333 @@ +import time +# from twisted.trial import unittest + +from pubnub import PubnubTwisted as Pubnub + +pubkey = "pub-c-37d3c709-c35e-487a-8b33-2314d9b62b28" +subkey = "sub-c-cd0b6288-cdf5-11e5-bcee-0619f8945a4f" +pubnub = Pubnub(pubkey, subkey) +pubnub_enc = Pubnub(pubkey, subkey, cipher_key="enigma") + + +# class PublishTests(unittest.TestCase): +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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + print(resp) + assert False + + pubnub.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub_enc.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub_enc.publish(channel, message, callback=_cb1, error=_err1) + + def _error(resp): + assert False + + pubnub_enc.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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub_enc.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub_enc.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub_enc.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub_enc.publish(channel, message, callback=_cb1, error=_err1) + + 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): + def _cb1(resp, ch=None): + assert resp[0] == 1 + + def _err1(resp): + assert False + + pubnub_enc.publish(channel, message, callback=_cb1, error=_err1) + + def _error(resp): + assert False + + pubnub_enc.subscribe(channel, callback=_cb, connect=_connect, error=_error) + + +x = 5 + + +def run_test(t): + global x + x += 5 + i = (x / 5) - 1 + + def _print(): + print('Running test ' + str(i)) + + pubnub.timeout(x, _print) + pubnub.timeout(x + 1, t) + + +def stop(): + pubnub.stop() + + +run_test(test_1) +run_test(test_2) +run_test(test_3) +run_test(test_4) +run_test(test_5) +run_test(test_6) +run_test(test_7) +run_test(test_8) +run_test(test_9) +run_test(test_10) +run_test(test_11) +run_test(stop) + +pubnub_enc.start() diff --git a/python-twisted/tests/unit-test-full.py b/python-twisted/tests/unit-test-full.py new file mode 100644 index 0000000..2335ef6 --- /dev/null +++ b/python-twisted/tests/unit-test-full.py @@ -0,0 +1,230 @@ +## www.pubnub.com - PubNub Real-time push service in the cloud. +# coding=utf8 + +## PubNub Real-time Push APIs and Notifications Framework +## Copyright (c) 2010 Stephen Blum +## http://www.pubnub.com/ + +## TODO Tests +## +## - wait 20 minutes, send a message, receive and success. +## - +## - +## +## + +## ----------------------------------- +## PubNub 3.1 Real-time Push Cloud API +## ----------------------------------- + +import sys +from pubnub import PubnubTwisted as Pubnub + +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' +secret_key = len(sys.argv) > 3 and sys.argv[3] or None +cipher_key = len(sys.argv) > 4 and sys.argv[4] or None +ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False + +## ----------------------------------------------------------------------- +## Command Line Options Supplied PubNub +## ----------------------------------------------------------------------- +pubnub_user_supplied_options = Pubnub( + publish_key, # OPTIONAL (supply None to disable) + subscribe_key, # REQUIRED + secret_key, # OPTIONAL (supply None to disable) + cipher_key, # OPTIONAL (supply None to disable) + ssl_on # OPTIONAL (supply None to disable) +) + +## ----------------------------------------------------------------------- +## High Security PubNub +## ----------------------------------------------------------------------- +pubnub_high_security = Pubnub( + ## Publish Key + 'pub-c-a30c030e-9f9c-408d-be89-d70b336ca7a0', + + ## Subscribe Key + 'sub-c-387c90f3-c018-11e1-98c9-a5220e0555fd', + + ## Secret Key + 'sec-c-MTliNDE0NTAtYjY4Ni00MDRkLTllYTItNDhiZGE0N2JlYzBl', + + ## Cipher Key + 'YWxzamRmbVjFaa05HVnGFqZHM3NXRBS73jxmhVMkjiwVVXV1d5UrXR1JLSkZFRr' + + 'WVd4emFtUm1iR0TFpUZvbiBoYXMgYmVlbxWkhNaF3uUi8kM0YkJTEVlZYVFjBYi' + + 'jFkWFIxSkxTa1pGUjd874hjklaTFpUwRVuIFNob3VsZCB5UwRkxUR1J6YVhlQWa' + + 'V1ZkNGVH32mDkdho3pqtRnRVbTFpUjBaeGUgYXNrZWQtZFoKjda40ZWlyYWl1eX' + + 'U4RkNtdmNub2l1dHE2TTA1jd84jkdJTbFJXYkZwWlZtRnKkWVrSRhhWbFpZVmFz' + + 'c2RkZmTFpUpGa1dGSXhTa3hUYTFwR1Vpkm9yIGluZm9ybWFNfdsWQdSiiYXNWVX' + + 'RSblJWYlRGcFVqQmFlRmRyYUU0MFpXbHlZV2wxZVhVNFJrTnR51YjJsMWRIRTJU' + + 'W91ciBpbmZvcm1hdGliBzdWJtaXR0ZWQb3UZSBhIHJlc3BvbnNlLCB3ZWxsIHJl' + + 'VEExWdHVybiB0am0aW9uIb24gYXMgd2UgcG9zc2libHkgY2FuLuhcFe24ldWVns' + + 'dSaTFpU3hVUjFKNllWaFdhRmxZUWpCaQo34gcmVxdWlGFzIHNveqQl83snBfVl3', + + ## 2048bit SSL ON - ENABLED TRUE + True +) + +## ----------------------------------------------------------------------- +## Channel | Message Test Data (UTF-8) +## ----------------------------------------------------------------------- +crazy = ' ~`â¦â§!@#$%^&*(顶顅Ȓ)+=[]\\{}|;\':",./<>?abcd' +many_channels = [str(x) + '-many_channel_test' for x in range(10)] +runthroughs = 0 +planned_tests = 2 +delivery_retries = 0 +max_retries = 10 + +## ----------------------------------------------------------------------- +## Unit Test Function +## ----------------------------------------------------------------------- + + +def test(trial, name): + if trial: + print('PASS: ' + name) + else: + print('- FAIL - ' + name) + + +def test_pubnub(pubnub): + global runthroughs, planned_tests, delivery_retries, max_retries + + ## ----------------------------------------------------------------------- + ## Many Channels + ## ----------------------------------------------------------------------- + def phase2(): + status = { + 'sent': 0, + 'received': 0, + 'connections': 0 + } + + def received(message, chan): + global runthroughs + + test(status['received'] <= status['sent'], 'many sends') + status['received'] += 1 + pubnub.unsubscribe({'channel': chan}) + if status['received'] == len(many_channels): + runthroughs += 1 + if runthroughs == planned_tests: + pubnub.stop() + + def publish_complete(info, chan): + global delivery_retries, max_retries + status['sent'] += 1 + test(info, 'publish complete') + test(info and len(info) > 2, 'publish response') + if not info[0]: + delivery_retries += 1 + if max_retries > delivery_retries: + sendit(chan) + + def sendit(chan): + tchan = chan + pubnub.publish({ + 'channel': chan, + 'message': "Hello World", + 'callback': (lambda msg: publish_complete(msg, tchan)) + }) + + def connected(chan): + status['connections'] += 1 + sendit(chan) + + def delivered(info): + if info and info[0]: + status['sent'] += 1 + + def subscribe(chan): + pubnub.subscribe({ + 'channel': chan, + 'connect': (lambda: connected(chan + '')), + 'callback': (lambda msg: received(msg, chan)) + }) + + ## Subscribe All Channels + for chan in many_channels: + subscribe(chan) + + ## ----------------------------------------------------------------------- + ## Time Example + ## ----------------------------------------------------------------------- + def time_complete(timetoken): + test(timetoken, 'timetoken fetch') + test(isinstance(timetoken, int), 'timetoken int type') + + pubnub.time({'callback': time_complete}) + + ## ----------------------------------------------------------------------- + ## Publish Example + ## ----------------------------------------------------------------------- + def publish_complete(info): + test(info, 'publish complete') + test(info and len(info) > 2, 'publish response') + + pubnub.history({ + 'channel': crazy, + 'limit': 10, + 'callback': history_complete + }) + + ## ----------------------------------------------------------------------- + ## History Example + ## ----------------------------------------------------------------------- + def history_complete(messages): + test(messages and len(messages) > 0, 'history') + test(messages, 'history') + + pubnub.publish({ + 'channel': crazy, + 'message': "Hello World", + 'callback': publish_complete + }) + + ## ----------------------------------------------------------------------- + ## Subscribe Example + ## ----------------------------------------------------------------------- + def message_received(message): + test(message, 'message received') + pubnub.unsubscribe({'channel': crazy}) + + def done(): + pubnub.unsubscribe({'channel': crazy}) + pubnub.publish({ + 'channel': crazy, + 'message': "Hello World", + 'callback': (lambda x: x) + }) + + def dumpster(message): + test(0, 'never see this') + + pubnub.subscribe({ + 'channel': crazy, + 'connect': done, + 'callback': dumpster + }) + + def connected(): + pubnub.publish({ + 'channel': crazy, + 'message': {'Info': 'Connected!'} + }) + + pubnub.subscribe({ + 'channel': crazy, + 'connect': connected, + 'callback': message_received + }) + + phase2() + +## ----------------------------------------------------------------------- +## Run Tests +## ----------------------------------------------------------------------- +test_pubnub(pubnub_user_supplied_options) +test_pubnub(pubnub_high_security) +pubnub_high_security.start() diff --git a/python/LICENSE b/python/LICENSE new file mode 100644 index 0000000..3efa392 --- /dev/null +++ b/python/LICENSE @@ -0,0 +1,27 @@ +PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks +Copyright (c) 2013 PubNub Inc. +http://www.pubnub.com/ +http://www.pubnub.com/terms + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks +Copyright (c) 2013 PubNub Inc. +http://www.pubnub.com/ +http://www.pubnub.com/terms diff --git a/python/README.md b/python/README.md new file mode 100644 index 0000000..2fce1ba --- /dev/null +++ b/python/README.md @@ -0,0 +1,400 @@ +## Contact support@pubnub.com for all questions + +#### [PubNub](http://www.pubnub.com) Real-time Data Network +##### Standalone Python Client + +#### Init + +``` +pubnub = Pubnub(publish_key="demo", subscribe_key="demo", ssl_on=False) + +``` + +#### PUBLISH + +``` +channel = 'hello_world' +message = 'Hello World !!!' + +# Synchronous usage +print pubnub.publish(channel=channel, message=message) + +# Asynchronous usage + +def callback(message): + print(message) + +pubnub.publish(channel=channel, message=message, callback=callback, error=callback) + +``` + + +#### SUBSCRIBE + +``` +# Listen for Messages + +channel = 'hello_world' + +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(channels=channel, callback=callback, error=error, + connect=connect, reconnect=reconnect, disconnect=disconnect) +``` + +#### SUBSCRIBE to group + +``` +# Listen for Messages + +channel_group = 'group1' + +def callback(message, channel_group, 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_group(channel_groups=channel_group, callback=callback, error=error, + connect=connect, reconnect=reconnect, disconnect=disconnect) +``` + +#### SUBSCRIBE Synchronous ( compatible with pre-3.5 ) +Runs in tight loop if callback return True. +Loop ends when callback return False +``` +# Listen for Messages + +channel = 'hello_world' + +def callback(message): + print(message) + return True + +pubnub.subscribe_sync(channel=channel, callback=callback) +``` + + +#### UNSUBSCRIBE + +``` +# Listen for Messages + +channel = 'hello_world' + +pubnub.unsubscribe(channel=channel) +``` + + +#### PRESENCE + +``` +# Listen for Presence Event Messages + +channel = 'hello_world' + +def callback(message, channel): + print(message) + + +def error(message): + print("ERROR : " + str(message)) + + + +pubnub.presence(channel=channel, callback=callback, error=error) +``` + +#### PRESENCE channel group + +``` +# Listen for Presence Event Messages + +channel_group = 'group1' + +def callback(message, channel_group, channel): + print(message) + + +def error(message): + print("ERROR : " + str(message)) + + + +pubnub.presence_group(channel_group=channel_group, callback=callback, error=error) +``` + +#### HERE_NOW + +``` +# Get info on who is here right now! + +channel = 'hello_world' + +# Synchronous usage +print pubnub.here_now(channel=channel) + + +# Asynchronous usage + +def callback(message): + print(message) + +pubnub.here_now(channel=channel, callback=callback, error=callback) +``` + +#### HISTORY + +``` +# Synchronous usage + +print pubnub.history(channel=channel, count=2) + +# Asynchronous usage + + +def callback(message): + print(message) + +pubnub.history(channel=channel, count=2, callback=callback, error=callback) +``` + +#### HISTORY (including timetokens) + +``` +# Synchronous usage + +print pubnub.history(channel, count=2, include_token=True) + +# Asynchronous usage + + +def callback(message): + print(message) + +pubnub.history(channel, count=2, include_token=True, callback=callback, error=callback) +``` + + +#### GRANT + +``` +authkey = "abcd" + +# Synchronous usage +print pubnub.grant(channel=channel, auth_key=authkey, read=True, write=True) + +# Asynchronous usage + + +def callback(message): + print(message) + +pubnub.grant(channel=channel, auth_key=authkey, read=True, write=True, callback=callback, error=callback) +``` + +#### AUDIT + +``` +channel = "hello_world" +authkey = "abcd" + +# Synchronous usage +print pubnub.audit(channel=channel, auth_key=authkey) + +# Asynchronous usage + + +def callback(message): + print(message) + +pubnub.audit(channel=channel, auth_key=authkey, callback=callback, error=callback) +``` + +#### REVOKE + +``` +channel = "hello_world" +authkey = "abcd" + +# Synchronous usage +print pubnub.revoke(channel=channel, auth_key=authkey) + +# Asynchronous usage + + +def callback(message): + print(message) + +pubnub.revoke(channel=channel, auth_key=authkey, callback=callback, error=callback) +``` + +### CHANNEL GROUP METHODS + +#### List Groups + +``` +# Synchronous usage + +print pubnub.channel_group_list_groups(namespace='aaa') + +# Asynchronous usage + +def callback(message): + print(message) + +pubnub.channel_group_list_groups(namespace='aaa', callback=callback, error=callback) + +``` + +#### List Channels + +``` +# Synchronous usage + +print pubnub.channel_group_list_channels(channel_group='dev:abcd') + +# Asynchronous usage + +def callback(message): + print(message) + +pubnub.channel_group_list_channels(channel_group='dev:abcd', callback=callback, error=callback) + +``` + +#### Add Channel + +``` +# Synchronous usage + +print pubnub.channel_group_add_channel(channel_group='dev:abcd', channel="hi") + +# Asynchronous usage + +def callback(message): + print(message) + +pubnub.channel_group_add_channel(channel_group='dev:abcd', channel="hi", callback=callback, error=callback) + +``` + + +#### Remove Channel + +``` +# Synchronous usage + +print pubnub.channel_group_remove_channel(channel_group='dev:abcd', channel="hi") + +# Asynchronous usage + +def callback(message): + print(message) + +pubnub.channel_group_remove_channel(channel_group='dev:abcd', channel="hi", callback=callback, error=callback) + +``` + + +#### List Channels + +``` +# Synchronous usage + +print pubnub.channel_group_list_channels(channel_group='dev:abcd') + +# Asynchronous usage + +def callback(message): + print(message) + +pubnub.channel_group_add_channel(channel_group='dev:abcd', callback=callback, error=callback) + +``` + +#### Grant + + +``` +# Synchronous usage + +print pubnub.grant(channel_group='dev:abcd', read=True, write=True, manage=True, auth_key="abcd") + +# Asynchronous usage + +def callback(message): + print(message) + +pubnub.grant(channel_group='dev:abcd', read=True, write=True, manage=True, auth_key="abcd", callback=callback, error=callback) + +``` + +#### Revoke + +``` +# Synchronous usage + +print pubnub.revoke(channel_group='dev:abcd', auth_key="abcd") + +# Asynchronous usage + +def callback(message): + print(message) + +pubnub.revoke(channel_group='dev:abcd', auth_key="abcd", callback=callback, error=callback) + +``` + + +#### Audit + +``` +# Synchronous usage + +print pubnub.audit(channel_group='dev:abcd') + +# Asynchronous usage + +def callback(message): + print(message) + +pubnub.audit(channel_group='dev:abcd', callback=callback, error=callback) + +``` + + + +## Contact support@pubnub.com for all questions diff --git a/python/examples/audit.py b/python/examples/audit.py new file mode 100644 index 0000000..b20e9ce --- /dev/null +++ b/python/examples/audit.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 'pam' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'pam' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'pam' +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' +authkey = "abcd" + +# Synchronous usage +print(pubnub.audit(channel, authkey)) + +# Asynchronous usage + + +def callback(message): + print(message) + +pubnub.audit(channel, authkey, callback=callback, error=callback) 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..5b391bf --- /dev/null +++ b/python/examples/console.py @@ -0,0 +1,719 @@ +# 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 atexit +import json +import os +import pygments +import readline +import sys +import threading +from cmd2 import Cmd, make_option, options +from datetime import datetime +from pygments.formatters import TerminalFormatter +from pygments.lexers import JsonLexer + +from pubnub import Pubnub + +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: + 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: + 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: + 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: + 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_ok("DISCONNECTED", r) + + def _reconnect(r): + print_ok("RECONNECTED", r) + + def _connect(r): + print_ok("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) + + unsub_list = [] + current_channel_list = pubnub.get_channel_array() + + for channel in channels: + pubnub.unsubscribe(channel) + if (channel in current_channel_list): + unsub_list.append(channel) + + # pubnub.unsubscribe(channel + '-pnpres') + # if (channel + '-pnpres' in current_channel_list): + # unsub_list.append(channel + ' (Presence)') + + if len(unsub_list) > 0: + print_ok('Unsubscribed from : ' + str(unsub_list)) + else: + print_error('Not subscribed to : ' + 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 get_channel_array(): + channels = pubnub.get_channel_array() + + for channel in channels: + if "-pnpres" in channel: + chname = channel.split("-pnpres")[0] + if chname not in channels: + continue + i = channels.index(chname) + 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" + "\n" + \ + "Commands can also be provided on command line while starting console (in quotes) ex. " + \ + "pubnub-console 'init -p demo -s demo'" + 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() + 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: + 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 = open(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: + 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"), + make_option('-p', '--presence', action="store_true", + dest="presence", + default=False, help="Unsubscribe from presence events ?") + ]) + 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 = [] + chs = pubnub.get_channel_array() + for ch in chs: + if '-pnpres' not in ch: + opts.channel.append(ch) + elif opts.presence is True: + opts.channel.append(ch) + + if opts.channel is None: + print_error("Missing channel") + return + + if not isinstance(opts.channel, list): + ch = [] + ch.append(opts.channel) + opts.channel = ch + + channels = [] + if opts.presence is True and opts.all is False: + for c in opts.channel: + if '-pnpres' not in c: + channels.append(c + '-pnpres') + + for c in opts.channel: + channels.append(c) + + _unsubscribe_command_handler(channels) + 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/cr.py b/python/examples/cr.py new file mode 100644 index 0000000..0c10693 --- /dev/null +++ b/python/examples/cr.py @@ -0,0 +1,52 @@ +# 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 'pam' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'pam' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'pam' +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, auth_key="abcd") +channel = 'hello_world' + + +def callback(message): + print(message) + +print(pubnub.revoke(channel_group='dev:abcd', auth_key="abcd")) +print(pubnub.audit(channel_group="dev:abcd")) +print(pubnub.grant(channel_group='dev:abcd', read=True, write=True, manage=True, auth_key="abcd")) +print(pubnub.channel_group_list_namespaces()) +print(pubnub.channel_group_list_groups(namespace='aaa')) +print(pubnub.channel_group_list_groups(namespace='foo')) +print(pubnub.channel_group_list_channels(channel_group='dev:abcd')) +print(pubnub.channel_group_add_channel(channel_group='dev:abcd', channel="hi")) +print(pubnub.channel_group_list_channels(channel_group='dev:abcd')) +print(pubnub.channel_group_remove_channel(channel_group='dev:abcd', channel="hi")) +print(pubnub.channel_group_list_channels(channel_group='dev:abcd')) + + +pubnub.revoke(channel_group='dev:abcd', auth_key="abcd", callback=callback, error=callback) +pubnub.audit(channel_group="dev:abcd", callback=callback, error=callback) +pubnub.grant(channel_group='dev:abcd', read=True, write=True, manage=True, auth_key="abcd", callback=callback, error=callback) +pubnub.channel_group_list_namespaces(callback=callback, error=callback) +pubnub.channel_group_list_groups(namespace='aaa', callback=callback, error=callback) +pubnub.channel_group_list_groups(namespace='foo', callback=callback, error=callback) +pubnub.channel_group_list_channels(channel_group='dev:abcd', callback=callback, error=callback) +pubnub.channel_group_add_channel(channel_group='dev:abcd', channel="hi", callback=callback, error=callback) +pubnub.channel_group_list_channels(channel_group='dev:abcd', callback=callback, error=callback) +pubnub.channel_group_remove_channel(channel_group='dev:abcd', channel="hi", callback=callback, error=callback) +pubnub.channel_group_list_channels(channel_group='dev:abcd', callback=callback, error=callback) diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py new file mode 100644 index 0000000..4c4bf5c --- /dev/null +++ b/python/examples/dev-console.py @@ -0,0 +1,273 @@ +# 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/ + +from pubnub import Pubnub +from optparse import OptionParser +from datetime import datetime +import threading + +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' + + +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: + 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: + print(msg) + + +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/grant.py b/python/examples/grant.py new file mode 100644 index 0000000..0fad10f --- /dev/null +++ b/python/examples/grant.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 'pam' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'pam' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'pam' +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' +authkey = "abcd" + +# Synchronous usage +print(pubnub.grant(channel, authkey, True, True)) + +# Asynchronous usage + + +def callback(message): + print(message) + +pubnub.grant(channel, authkey, True, True, callback=callback, error=callback) diff --git a/python/examples/heartbeat.py b/python/examples/heartbeat.py new file mode 100644 index 0000000..a58646a --- /dev/null +++ b/python/examples/heartbeat.py @@ -0,0 +1,106 @@ +# 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 gevent.monkey +import random +import sys +from datetime import datetime +from pubnub import Pubnub as Pubnub + +gevent.monkey.patch_all() + +# from pubnub import PubnubTornado as Pubnub +# from pubnub import PubnubTwisted as Pubnub + +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'ds' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'ds' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'ds' +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, uuid="test-" + str(random.random())) + + +def x(url): + print(url) + + +# pubnub.set_http_debug(x) + +channel = 'ab,cd,ef' +channel_group = "abg,cdg" + + +def set_heartbeat(*argv): + print("Change Heartbeat to ", argv[0]) + pubnub.set_heartbeat(argv[0], argv[1], argv[2]) + + +def set_heartbeat_interval(*argv): + pubnub.set_heartbeat_interval(argv[0]) + + +# pubnub.timeout(0, set_heartbeat, 8) + +# 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.channel_group_add_channel("abg", "abcd") +pubnub.channel_group_add_channel("cdg", "efgh") + +pubnub.subscribe(channels=channel, callback=callback, error=callback, + connect=connect, reconnect=reconnect, disconnect=disconnect) + +pubnub.subscribe_group(channel_groups=channel_group, callback=callback, error=callback, + connect=connect, reconnect=reconnect, disconnect=disconnect) + + +def cb(resp): + print(datetime.now().strftime('%H:%M:%S'), resp) + + +def err(resp): + print(datetime.now().strftime('%H:%M:%S'), resp) + + +pubnub.timeout(5, set_heartbeat, 120, cb, err) +pubnub.timeout(90, set_heartbeat, 60, cb, err) +pubnub.timeout(180, set_heartbeat, 30, cb, err) +pubnub.timeout(240, set_heartbeat, 15, cb, err) +pubnub.timeout(300, set_heartbeat, 8, cb, err) +# pubnub.timeout(360, pubnub.stop_heartbeat) + + +''' +import time +while True: + time.sleep(10) +''' + +pubnub.start() diff --git a/python/examples/here-now.py b/python/examples/here-now.py new file mode 100644 index 0000000..0eb8994 --- /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.py b/python/examples/history.py new file mode 100644 index 0000000..8691a4b --- /dev/null +++ b/python/examples/history.py @@ -0,0 +1,47 @@ +# 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) + +# Synchronous usage + +print(pubnub.history(channel, count=2, include_token=True)) + +# Asynchronous usage + + +def callback(message): + print(message) + +pubnub.history(channel, count=2, include_token=True, callback=callback, error=callback) diff --git a/python/examples/pam_demo/demo.py b/python/examples/pam_demo/demo.py new file mode 100644 index 0000000..1c68787 --- /dev/null +++ b/python/examples/pam_demo/demo.py @@ -0,0 +1,126 @@ +from gevent.monkey import patch_all +from pubnub import Pubnub +import random +import json + +patch_all() + +rand = str(random.randint(1, 99999999)) + + +def get_unique(s): + return 'str-' + rand + '-' + s + + +# public channel +# This is the channel all clients announce themselves on -- or more generally speaking, a channel you expect the client +# to "check-in" on to announce his state + +# channel_public = get_unique("channel_public") +channel_public = "channel_public" + +# server auth key +# Only the server has/knows about this auth token. It will be used to grant read on the "check-in" Presence channel + +# server_auth_token = get_unique("server_auth_token") +server_auth_token = "server_auth_token" + +# client auth key +# only clients will use this authey -- it does not provide presence channel read access + +# client_auth_token = get_unique("client_auth_token") +client_auth_token = "client_auth_token" + +# each client must have a unique id -- a UUID, for presence information/state to bind to + +# client uuid +client_uuid = get_unique("client_uuid") + +# server uuid +server_uuid = get_unique("server_uuid") + +# For the demo, we'll implement a SERVER called server, who is the authoritative 'admin' entity in the system +# We'll also implement a CLIENT called client, who is an arbitrary hardware device member of the network + +# Please swap out the default 'pam' demo keys with your own PAM-enabled keys + +# init server object +server = Pubnub(publish_key="pam", subscribe_key="pam", secret_key="pam", auth_key=server_auth_token, uuid=server_uuid) + +# init client object +client = Pubnub(publish_key="pam", subscribe_key="pam", auth_key=client_auth_token, uuid=client_uuid) + +# To access a Presence channel with PAM, its format is CHANNELNAME-pnpres + +# Grant permission to server auth keys +# grant r/w to public, and r/w public Presence (public-pnpres) + +print(server.grant(channel=channel_public, auth_key=server_auth_token, read=True, write=True)) +print(server.grant(channel=channel_public + '-pnpres', auth_key=server_auth_token, read=True, write=True)) + +# Grant permission to client auth keys +# grant r/w to public, and w-only access to public Presence (public-pnpres) +print(server.grant(channel=channel_public, auth_key=client_auth_token, read=True, write=False)) +print(server.grant(channel=channel_public + '-pnpres', auth_key=client_auth_token, read=False, write=False)) + + +# Now, we'll run it to watch it work as advertised... + +# Define some simple callabcks for the Server and Client + +def _server_message_callback(message, channel): + print("Server heard: " + json.dumps(message)) + + +def _client_message_callback(message, channel): + print("Client heard: " + json.dumps(message)) + + +def _client_error_callback(error, channel): + print("Client Error: " + error + " on channel " + channel) + print("TTL on grant expired, or token was invalid, or revoked." + " Client will now unsubscribe from this unauthorized channel.") + client.unsubscribe(channel=channel) + + +def _server_error_callback(error, channel): + print("Server Error: " + error + " on channel " + channel) + print("TTL on grant expired, or token was revoked. Server will now unsubscribe from this unauthorized channel.") + server.unsubscribe(channel=channel) + + +def _server_presence_callback(message, channel): + print(message) + if 'action' in message: + if message['action'] == 'join' and message['uuid'] == client_uuid: + print("Server can see that client with UUID " + message['uuid'] + " has a state of " + json.dumps( + message['data'])) + + +def _client_presence_callback(message, channel): + print(message) + if 'action' in message: + if message['action'] == 'join' and message['uuid'] == client_uuid: + print("Client can see that client with UUID " + message['uuid'] + " has a state of " + json.dumps( + message['data'])) + + +# server subscribes to public channel +server.subscribe(channels=channel_public, callback=_server_message_callback, error=_server_error_callback) + +# server subscribes to presence events on public channel +# presence() is a convienence method that subscribes to channel-pnpres with special logic for handling +# presence-event formatted messages + +# uncomment out to see server able to read on presence channel +server.presence(channel=channel_public, callback=_server_presence_callback, error=_server_error_callback) + +# now if the client tried to subscribe on the presence channel, and therefore, get state info +# he is explicitly denied! + +# uncomment out to see client not able to read on presence channel +client.presence(channel=channel_public, callback=_client_presence_callback, error=_client_error_callback) + +# client subscribes to public channel +client.subscribe(channels=channel_public, state={"myKey": get_unique("foo")}, callback=_client_message_callback, + error=_client_error_callback) diff --git a/python/examples/presence.py b/python/examples/presence.py new file mode 100644 index 0000000..b55bb0b --- /dev/null +++ b/python/examples/presence.py @@ -0,0 +1,32 @@ +# 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, daemon=False) + +channel = 'b' + + +# Asynchronous usage +def callback(message, channel): + print(message) + +pubnub.presence(channel, callback=callback) diff --git a/python/examples/publish.py b/python/examples/publish.py new file mode 100644 index 0000000..a645ad6 --- /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, pooling=False) +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..a1915ed --- /dev/null +++ b/python/examples/pubnub-console/pubnub-console @@ -0,0 +1,724 @@ +## 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_ok("DISCONNECTED", r) + + def _reconnect(r): + print_ok("RECONNECTED", r) + + def _connect(r): + print_ok("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) + + unsub_list = [] + current_channel_list = pubnub.get_channel_array() + + for channel in channels: + pubnub.unsubscribe(channel) + if (channel in current_channel_list): + unsub_list.append(channel) + + #pubnub.unsubscribe(channel + '-pnpres') + #if (channel + '-pnpres' in current_channel_list): + # unsub_list.append(channel + ' (Presence)') + + if len(unsub_list) > 0: + print_ok('Unsubscribed from : ' + str(unsub_list)) + else: + print_error('Not subscribed to : ' + 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: + chname = channel.split("-pnpres")[0] + if chname not in channels: + continue + i = channels.index(chname) + 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" + "\n" + \ + "Commands can also be provided on command line while starting console (in quotes) ex. " + \ + "pubnub-console 'init -p demo -s demo'" + 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"), + make_option('-p', '--presence', action="store_true", + dest="presence", + default=False, help="Unsubscribe from presence events ?") + ]) + 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 = [] + chs = pubnub.get_channel_array() + for ch in chs: + if '-pnpres' not in ch: + opts.channel.append(ch) + elif opts.presence is True: + opts.channel.append(ch) + + if opts.channel is None: + print_error("Missing channel") + return + + if not isinstance(opts.channel, list): + ch = [] + ch.append(opts.channel) + opts.channel = ch + + channels = [] + if opts.presence is True and opts.all is False: + for c in opts.channel: + if '-pnpres' not in c: + channels.append(c + '-pnpres') + + for c in opts.channel: + channels.append(c) + + _unsubscribe_command_handler(channels) + 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..5ee5fd9 --- /dev/null +++ b/python/examples/pubnub-console/setup.py @@ -0,0 +1,27 @@ +from setuptools import setup + +setup( + name='pubnub-console', + version='3.5.2', + 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.2', + '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/revoke.py b/python/examples/revoke.py new file mode 100644 index 0000000..23bc110 --- /dev/null +++ b/python/examples/revoke.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 'pam' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'pam' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'pam' +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' +authkey = "abcd" + +# Synchronous usage +print(pubnub.revoke(channel, authkey)) + +# Asynchronous usage + + +def callback(message): + print(message) + +pubnub.revoke(channel, authkey, callback=callback, error=callback) diff --git a/python/examples/start-console.sh b/python/examples/start-console.sh new file mode 100644 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/state.py b/python/examples/state.py new file mode 100644 index 0000000..f1c92c6 --- /dev/null +++ b/python/examples/state.py @@ -0,0 +1,123 @@ +# 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 +import time +from gevent import monkey +from pubnub import Pubnub + +monkey.patch_all() + + +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) + + +def log(a): + print(a) + + +pubnub.set_http_debug(log) + +# Synchronous usage +print(pubnub.state(channel='abcd', uuid='33c72389-1110-4312-9444-4dd24ade1d57', state={'a': 'b'})) + + +# Asynchronous usage + + +def callback(message): + print(message) + + +pubnub.state(channel='abcd', uuid='33c72389-1110-4312-9444-4dd24ade1d57', state={'a': 'b'}, callback=callback, + error=callback) + +time.sleep(5) + +# Synchronous usage +print(pubnub.state(channel='abcd', uuid='33c72389-1110-4312-9444-4dd24ade1d57')) + + +# Asynchronous usage + + +def callback(message): + print(message) + + +pubnub.state(channel='abcd', uuid='33c72389-1110-4312-9444-4dd24ade1d57', callback=callback, error=callback) + +time.sleep(5) + +# Synchronous usage +print(pubnub.state(channel='abcd')) + + +# Asynchronous usage + + +def callback(message): + print(message) + + +pubnub.state(channel='abcd', callback=callback, error=callback) + +time.sleep(5) + +# Synchronous usage +print(pubnub.state(channel='abcd', state={'a': 'b'})) + + +# Asynchronous usage + + +def callback(message): + print(message) + + +pubnub.state(channel='abcd', state={'a': 'b'}, callback=callback, error=callback) + +time.sleep(5) + +# Synchronous usage +print(pubnub.state(channel='abcd')) + + +# Asynchronous usage + + +def callback(message): + print(message) + + +pubnub.state(channel='abcd', callback=callback, error=callback) + +time.sleep(5) + +# Synchronous usage +print(pubnub.state(channel='abcd')) + + +# Asynchronous usage + + +def callback(message): + print(message) + + +pubnub.state(channel='abcd', callback=callback, error=callback) diff --git a/python/examples/subscribe.py b/python/examples/subscribe.py new file mode 100644 index 0000000..8ee0099 --- /dev/null +++ b/python/examples/subscribe.py @@ -0,0 +1,53 @@ +# 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 +import time +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, daemon=True) + +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(channels=channel, callback=callback, error=callback, + connect=connect, reconnect=reconnect, disconnect=disconnect) + +while True: + time.sleep(10) diff --git a/python/examples/subscribe_group.py b/python/examples/subscribe_group.py new file mode 100644 index 0000000..b6228f6 --- /dev/null +++ b/python/examples/subscribe_group.py @@ -0,0 +1,69 @@ +# 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 as 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 'abcd' +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 = 'ab' + + +# Asynchronous usage + +def callback_abc(message, channel, real_channel): + print(str(message) + ' , ' + channel + ', ' + real_channel) + pubnub.unsubscribe_group(channel_group='abc') + # pubnub.stop() + + +def callback_d(message, channel): + print(str(message) + ' , ' + channel) + + +def error(message): + print("ERROR : " + str(message)) + + +def connect_abc(message): + print("CONNECTED " + str(message)) + + +def connect_d(message): + print("CONNECTED " + str(message)) + pubnub.unsubscribe(channel='d') + + +def reconnect(message): + print("RECONNECTED " + str(message)) + + +def disconnect(message): + print("DISCONNECTED " + str(message)) + + +print(pubnub.channel_group_add_channel(channel_group='abc', channel="b")) + +pubnub.subscribe_group(channel_groups='abc', callback=callback_abc, error=error, + connect=connect_abc, reconnect=reconnect, disconnect=disconnect) + +pubnub.subscribe(channels='d', callback=callback_d, error=error, + connect=connect_d, reconnect=reconnect, disconnect=disconnect) + +pubnub.start() diff --git a/python/examples/where-now.py b/python/examples/where-now.py new file mode 100644 index 0000000..dd18a67 --- /dev/null +++ b/python/examples/where-now.py @@ -0,0 +1,38 @@ +# 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 gevent import monkey +from pubnub import Pubnub + +monkey.patch_all() + +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) + +# Synchronous usage +print(pubnub.where_now(uuid='33c72389-1110-4312-9444-4dd24ade1d57')) + + +# Asynchronous usage + + +def callback(message): + print(message) + + +pubnub.where_now(uuid='33c72389-1110-4312-9444-4dd24ade1d57', callback=callback, error=callback) diff --git a/python/examples/wildcard_subscribe.py b/python/examples/wildcard_subscribe.py new file mode 100644 index 0000000..b3e542e --- /dev/null +++ b/python/examples/wildcard_subscribe.py @@ -0,0 +1,96 @@ +from gevent import monkey +from pubnub import Pubnub + +monkey.patch_all() + + +pubnub = Pubnub(publish_key="ds", subscribe_key="ds", + secret_key="ds", ssl_on=False) + + +# Wildcard Subscribe without presence + +def a(): + channel_wc = "a.*" + channel = "a.b" + + def callback(message1, channel1, real_channel=None): + print(channel1 + " : " + real_channel + " : " + str(message1)) + + def error(message): + print("ERROR : " + str(message)) + + def connect(channel1=None): + print("Connect on " + channel1) + print(pubnub.publish(channel=channel, message="a")) + + def disconnect(channel1=None): + print("Disconnect on " + channel1) + + def reconnect(channel1=None): + print("Reconnect on " + channel1) + + pubnub.subscribe(channels=channel_wc, callback=callback, error=callback, + connect=connect, disconnect=disconnect, reconnect=reconnect) + + +# Wildcard Subscribe with presence + +def b(): + channel_wc = "b.*" + channel = "b.c" + + def callback(message1, channel1, real_channel=None): + print(channel1 + " : " + real_channel + " : " + str(message1)) + + def error(message): + print("ERROR : " + str(message)) + + def presence(message1, channel1, real_channel=None): + print(channel1 + " : " + real_channel + " : " + str(message1)) + + def connect(channel1=None): + print("Connect on " + channel1) + print(pubnub.publish(channel=channel, message="b")) + + def disconnect(channel1=None): + print("Disconnect on " + channel1) + + def reconnect(channel1=None): + print("Reconnect on " + channel1) + + pubnub.subscribe(channels=channel_wc, callback=callback, error=callback, + connect=connect, disconnect=disconnect, reconnect=reconnect, presence=presence) + + +# Wildcard Subscribe and unsubscribe + +def c(): + channel_wc = "c.*" + channel = "c.d" + + def callback(message1, channel1, real_channel=None): + print(channel1 + " : " + real_channel + " : " + str(message1)) + pubnub.unsubscribe(channel="c.*") + print(pubnub.publish(channel=channel, message="c1")) + + def error(message): + print("ERROR : " + str(message)) + + def connect(channel1=None): + print("Connect on " + channel1) + print(pubnub.publish(channel=channel, message="c")) + + def disconnect(channel1=None): + print("Disconnect on " + channel1) + + def reconnect(channel1=None): + print("Reconnect on " + channel1) + + pubnub.subscribe(channels=channel_wc, callback=callback, error=callback, + connect=connect, disconnect=disconnect, reconnect=reconnect) + + +a() +b() +c() 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/test_cg.py b/python/tests/test_cg.py new file mode 100644 index 0000000..154611f --- /dev/null +++ b/python/tests/test_cg.py @@ -0,0 +1,96 @@ +from pubnub import Pubnub +import random + +pubnub = Pubnub("demo", "demo") +pubnub.set_u(True) + + +def rand_str(s): + return str(s) + '-' + str(random.randint(1, 100000000000)) + + +def test_1(): + channel = rand_str('channel') + channel2 = rand_str('channel') + channel_group = rand_str('group') + channel_group2 = rand_str('group') + namespace = rand_str('ns') + + resp = pubnub.channel_group_add_channel(channel_group=namespace + ':' + channel_group, channel=channel) + assert resp['status'] == 200 + assert resp['message'] == 'OK' + assert resp['error'] == False + + resp = pubnub.channel_group_add_channel(channel_group=namespace + ':' + channel_group, channel=channel2) + assert resp['status'] == 200 + assert resp['message'] == 'OK' + assert resp['error'] == False + + resp = pubnub.channel_group_add_channel(channel_group=namespace + ':' + channel_group2, channel=channel) + assert resp['status'] == 200 + assert resp['message'] == 'OK' + assert resp['error'] == False + + resp = pubnub.channel_group_add_channel(channel_group=namespace + ':' + channel_group2, channel=channel2) + assert resp['status'] == 200 + assert resp['message'] == 'OK' + assert resp['error'] == False + + resp = pubnub.channel_group_list_channels(channel_group=namespace + ':' + channel_group) + assert channel in resp['payload']['channels'] + assert channel2 in resp['payload']['channels'] + assert len(resp['payload']['channels']) == 2 + + resp = pubnub.channel_group_remove_channel(channel_group=namespace + ':' + channel_group, channel=channel2) + print(resp) + assert resp['status'] == 200 + assert resp['message'] == 'OK' + assert resp['error'] == False + + resp = pubnub.channel_group_list_channels(channel_group=namespace + ':' + channel_group) + print(resp) + assert channel in resp['payload']['channels'] + assert len(resp['payload']['channels']) == 1 + + resp = pubnub.channel_group_list_channels(channel_group=namespace + ':' + channel_group2) + assert channel in resp['payload']['channels'] + assert channel2 in resp['payload']['channels'] + assert len(resp['payload']['channels']) == 2 + + resp = pubnub.channel_group_remove_channel(channel_group=namespace + ':' + channel_group2, channel=channel2) + print(resp) + assert resp['status'] == 200 + assert resp['message'] == 'OK' + assert resp['error'] == False + + resp = pubnub.channel_group_list_channels(channel_group=namespace + ':' + channel_group2) + print(resp) + assert channel in resp['payload']['channels'] + assert len(resp['payload']['channels']) == 1 + + resp = pubnub.channel_group_list_groups(namespace=namespace) + assert channel_group in resp['payload']['groups'] + assert channel_group2 in resp['payload']['groups'] + assert len(resp['payload']['groups']) == 2 + + resp = pubnub.channel_group_remove_group(channel_group=namespace + ':' + channel_group2) + print(resp) + assert resp['status'] == 200 + assert resp['message'] == 'OK' + assert resp['error'] == False + + resp = pubnub.channel_group_list_groups(namespace=namespace) + assert channel_group in resp['payload']['groups'] + assert len(resp['payload']['groups']) == 1 + + resp = pubnub.channel_group_list_namespaces() + assert namespace in resp['payload']['namespaces'] + + resp = pubnub.channel_group_remove_namespace(namespace=namespace) + print(resp) + assert resp['status'] == 200 + assert resp['message'] == 'OK' + assert resp['error'] == False + + resp = pubnub.channel_group_list_namespaces() + assert namespace not in resp['payload']['namespaces'] diff --git a/python/tests/test_grant.py b/python/tests/test_grant.py new file mode 100644 index 0000000..1789d60 --- /dev/null +++ b/python/tests/test_grant.py @@ -0,0 +1,90 @@ +from pubnub import Pubnub +import time + +subkey = "sub-c-9aeec0d4-cdf4-11e5-bcee-0619f8945a4f" +pubkey = "pub-c-b3fdf8fc-4516-4ab2-8836-6fb22ba7870d" +secretkey = "sec-c-ZDQwNTUwMDctZDViYi00MzhlLTg2NTctYjViZDcwNTA5Zjhj" +pubnub = Pubnub(pubkey, subkey) +pubnub_pam = Pubnub(pubkey, subkey, secretkey) +pam_timeout = 10 + + +# 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) + print(resp) + assert resp['message'] == 'Success' + assert resp['payload'] == { + 'auths': {'abcd': {'r': 1, 'w': 1, 'm': 0}}, + 'subscribe_key': subkey, + '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, 'm': 0}}, + 'subscribe_key': subkey, + '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, 'm': 0}}, + 'subscribe_key': subkey, + '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, 'm': 0}}, + 'subscribe_key': subkey, + '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, 'm': 0}}, + 'subscribe_key': subkey, + 'level': 'user', 'channel': 'abcd', 'ttl': 10 + } + + +# 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.set_auth_key(auth_key) + resp = pubnub_pam.grant(channel=channel, read=True, write=True, + auth_key=auth_key, ttl=10) + assert resp == { + 'message': 'Success', + 'payload': {'auths': {auth_key: {'r': 1, 'w': 1, 'm': 0}}, + 'subscribe_key': subkey, + 'level': 'user', 'channel': channel, 'ttl': 10} + } + time.sleep(pam_timeout) + resp = pubnub.publish(channel=channel, message=message) + assert resp[0] == 1 diff --git a/python/tests/test_history.py b/python/tests/test_history.py new file mode 100644 index 0000000..64ee7f0 --- /dev/null +++ b/python/tests/test_history.py @@ -0,0 +1,65 @@ +from pubnub import Pubnub +import time +import random +from nose.tools import with_setup + + +pubnub = Pubnub("ds", "ds") +pubnub_enc = Pubnub(publish_key="ds", subscribe_key="ds", cipher_key="enigma") +pubnub_pam = Pubnub(publish_key="pam", subscribe_key="pam", secret_key="pam") + + +def rand(msg): + return "rand-" + str(random.random()) + "-" + msg + +channel = rand("channel") +channel_enc = rand("channel_enc") +channel_pam = rand("channel_pam") + +messages = [] + + +def setup_func(): + pubnub_pam.grant(channel=channel_pam, read=True, write=True, ttl=144000) + + for i in range(0, 20): + msg = rand("message-" + str(i)) + messages.append(msg) + print(pubnub.publish(channel=channel, message=msg)) + # Fails with Python 3 + # print(pubnub_enc.publish(channel=channel_enc, message=msg)) + print(pubnub_pam.publish(channel=channel_pam, message=msg)) + + +@with_setup(setup_func) +def test_1(): + time.sleep(3) + hresp = pubnub.history(channel=channel, count=20) + # Fails with Python 3 + # hresp2 = pubnub_enc.history(channel=channel_enc, count=20) + hresp3 = pubnub_pam.history(channel=channel_pam, count=20) + hresp4 = pubnub_pam.history(channel=channel_pam + "no_rw", count=20) + assert hresp[0] == messages + # Fails with Python 3 + # assert hresp2[0] == messages + assert hresp3[0] == messages + assert hresp4['message'] == 'Forbidden' + assert channel_pam + "no_rw" in hresp4['payload']['channels'] + + +def test_2(): + time.sleep(3) + hresp = pubnub.history(channel=channel, count=20, include_token=True) + # Fails with Python 3 + # hresp2 = pubnub_enc.history(channel=channel_enc, count=20, include_token=True) + hresp3 = pubnub_pam.history(channel=channel_pam, count=20, include_token=True) + hresp4 = pubnub_pam.history(channel=channel_pam + "no_rw", count=20, include_token=True) + assert len(hresp[0]) == len(messages) + assert hresp[0][0]['timetoken'] + # Fails with Python 3 + # assert len(hresp2[0]) == len(messages) + # assert hresp2[0][0]['timetoken'] + assert len(hresp3[0]) == len(messages) + assert hresp3[0][0]['timetoken'] + assert hresp4['message'] == 'Forbidden' + assert channel_pam + "no_rw" in hresp4['payload']['channels'] diff --git a/python/tests/test_wildcard.py b/python/tests/test_wildcard.py new file mode 100644 index 0000000..b563975 --- /dev/null +++ b/python/tests/test_wildcard.py @@ -0,0 +1,360 @@ +# 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 time +import random +from pubnub import Pubnub +from inspect import currentframe, getouterframes +from gevent import monkey + +monkey.patch_all() + + +def get_line(): + # print getouterframes(currentframe())[3] + return getouterframes(currentframe())[2][2] + + +DELAY = 5 + +RESULTS = {} + + +def check_tests(): + for i in RESULTS: + test = RESULTS[i] + if test['done'] is False: + if test['expect'] == test['passed']: + green(i + " PASSED " + str(test['passed'])) + else: + red(i + " FAILED " + str(test['failed'])) + test['done'] = True + + +def init(conf, name, expect): + # check_tests() + print("\n\n") + RESULTS[name + conf] = {'passed': 0, 'failed': 0, 'expect': 0, 'done': False, 'conf': conf} + RESULTS[name + conf]['expect'] = expect + + +def get_random(): + return str(random.randint(1, 99999)) + + +def red(name): + print('\033[1;31m' + name + '\033[1;m') + + +def green(name): + print('\033[1;92m' + name + '\033[1;m') + + +def test(cond, desc=None, test_name=None, conf=None): + if (cond): + green("[" + test_name + " " + str(conf) + " ""][" + str(get_line()) + "] PASS : " + str(desc)) + RESULTS[test_name + conf]['passed'] = RESULTS[test_name + str(conf)]['passed'] + 1 + else: + red("[" + test_name + " " + str(conf) + " ""][" + str(get_line()) + "] FAIL : " + str(desc)) + RESULTS[test_name + conf]['failed'] = RESULTS[test_name + str(conf)]['failed'] + 1 + # exit(0) + + +def run_tests(tests): + for test in tests: + if len(test) > 4: + test[1](test[2], test[3], test[0], test[4]) + else: + test[1](test[2], test[3], test[0]) + time.sleep(DELAY) + check_tests() + + +def test_1(pubnub, pubnub2, conf=None, msg=None): + init(conf, "test_1", 6) + r = get_random() + channel_wc = r + "-" + "test_1-ab.*" + message = msg if msg is not None else (r + "-" + "test_1_hi") + channel = r + "-" + "test_1-ab.d" + + # Asynchronous usage + def callback(message1, channel1, real_channel=None): + # print(str(message1) + ' : ' + str(channel1) + ' : ' + str(real_channel)) + test(message1 == str(message, 'utf-8'), "message received", "test_1", conf) + test(channel1 == channel_wc, "Channel == wildcard channel", "test_1", conf) + test(real_channel == channel, "Real channel == publish channel", "test_1", conf) + + def error(message): + print("ERROR : " + str(message)) + + def connect(channel1=None): + test(True, "Connect Called", "test_1", conf) + test(channel1 == channel_wc, "Channel param in Connect same as wildcard", "test_1", conf) + + def _callback(message): + test(message[0] == 1, "Publish Successful", "test_1", conf) + + def _error(message): + test(False, "Publish Successful", "test_1", conf) + + pubnub.publish(channel=channel, message=message, callback=_callback, error=_error) + + pubnub.subscribe(channels=channel_wc, callback=callback, error=callback, connect=connect) + + +def test_2(pubnub, pubnub2, conf=None, msg=None): + init(conf, "test_2", 8) + r = get_random() + channel_wc = r + "-" + "test_2-ab.*" + message = msg if msg is not None else (r + "-" + "test_2_hi") + channel = r + "-" + "test_2-ab.d" + + # Asynchronous usage + def callback(message1, channel1, real_channel=None): + # print(str(message1) + ' : ' + str(channel1) + ' : ' + str(real_channel)) + test(message1 == str(message, 'utf-8'), "message received", "test_2", conf) + test(channel1 == channel_wc, "Channel == wildcard channel", "test_2", conf) + test(real_channel == channel, "Real channel == publish channel", "test_2", conf) + + def error(message): + print("ERROR : " + str(message)) + + def presence(message, channel1, real_channel=None): + if (pubnub.uuid == message['uuid']): + test(channel_wc == real_channel, "On pubnub subscribe presence event as wildcard as real channel", "test_2", + conf) + elif (pubnub2.uuid == message['uuid']): + test(channel == real_channel, "On pubnub2 subscribe presence event as channel as real channel", "test_2", + conf) + else: + test(False, "Wrong presence event", "test_2", conf) + + def connect(channel1=None): + # print(channel1) + test(True, "Connect Called", "test_2", conf) + test(channel1 == channel_wc, "Channel param in Connect same as wildcard", "test_2", conf) + + def _callback(message): + test(message[0] == 1, "Publish Successful", "test_2", conf) + + def _error(message): + test(False, "Publish Successful", "test_2", conf) + + pubnub.publish(channel=channel, message=message, callback=_callback, error=_error) + + def _callback(message, channel1): + pass + + def _error(message): + test(False, "Error in subscribe", "test_2", conf) + + pubnub2.subscribe(channels=channel, callback=_callback, error=_error) + + pubnub.subscribe(channels=channel_wc, callback=callback, error=callback, connect=connect, presence=presence) + + +def test_3(pubnub, pubnub2, conf=None, msg=None): + init(conf, "test_3", 6) + + r = get_random() + channel_wc = r + "-" + "test_3-ab.*" + message = msg if msg is not None else (r + "-" + "test_3_hi") + channel = r + "-" + "test_3-ab.d" + + # Asynchronous usage + def callback(message1, channel1, real_channel=None): + if 'action' in message1: + test(False, "Presence event received without presence callback", "test_3", conf) + return + + test(message1 == str(message, 'utf-8'), "message received", "test_3", conf) + test(channel1 == channel_wc, "Channel == wildcard channel", "test_3", conf) + test(real_channel == channel, "Real channel == publish channel", "test_3", conf) + + def error(message): + print("ERROR : " + str(message)) + + def connect(channel1=None): + # print(channel1) + test(True, "Connect Called", "test_3", conf) + test(channel1 == channel_wc, "Channel param in Connect same as wildcard", "test_3", conf) + + def _callback(message): + test(message[0] == 1, "Publish Successful", "test_3", conf) + + def _error(message): + test(False, "Publish Successful", "test_3", conf) + + pubnub.publish(channel=channel, message=message, callback=_callback, error=_error) + + def _callback(message, channel1): + pass + + def _error(message): + test(False, "Error in subscribe", "test_3", conf) + + pubnub2.subscribe(channels=channel, callback=_callback, error=_error) + + pubnub.subscribe(channels=channel_wc, callback=callback, error=callback, connect=connect) + + +def test_4(pubnub, pubnub2, conf=None, msg=None): + init(conf, "test_4", 18) + + r = get_random() + channel_wc = r + "-" + "test_4-ab.*" + channel_group = r + "-" + "test_4_group" + channel_g = r + "-" + "test_4_group_channel" + message = msg if msg is not None else (r + "-" + "test_4_hi") + channel = r + "-" + "test_4-ab.d" + channel_n = r + "-" + "test_4-a" + + def _callback(resp): + # Asynchronous usage + def callback_wc(message1, channel1, real_channel=None): + test(message1 == str(message, 'utf-8'), "message received", "test_4", conf) + test(channel1 == channel_wc, "Channel == wildcard channel", "test_4", conf) + test(real_channel == channel, "Real channel == publish channel", "test_4", conf) + + def callback_group(message1, channel1, real_channel=None): + test(message1 == str(message, 'utf-8'), "message received", "test_4", conf) + test(channel1 == channel_group, "Channel == group", "test_4", conf) + test(real_channel == channel_g, "Real channel == publish channel", "test_4", conf) + + def callback_n(message1, channel1, real_channel=None): + test(message1 == str(message, 'utf-8'), "message received", "test_4", conf) + test(channel1 == channel_n, "Channel == channel", "test_4", conf) + test(real_channel == channel_n, "Real channel == publish channel", "test_4", conf) + + def error(message): + print("ERROR : " + str(message)) + + def connect_wc(channel1=None): + test(True, "Connect Called", "test_4", conf) + test(channel1 == channel_wc, "Channel param in Connect same as wildcard", "test_4", conf) + + def _callback(message): + test(message[0] == 1, "Publish Successful", "test_4", conf) + + def _error(message): + test(False, "Publish Successful", "test_4", conf) + + pubnub.publish(channel=channel, message=message, callback=_callback, error=_error) + + def connect_group(channel1=None): + # print(channel1) + test(True, "Connect Called", "test_4", conf) + test(channel1 == channel_group, "Channel param in Connect same as channel_group", "test_4", conf) + + def _callback(message): + test(message[0] == 1, "Publish Successful", "test_4", conf) + + def _error(message): + test(False, "Publish Successful", "test_4", conf) + + pubnub.publish(channel=channel_g, message=message, callback=_callback, error=_error) + + def connect_n(channel1=None): + # print(channel1) + test(True, "Connect Called", "test_4", conf) + test(channel1 == channel_n, "Channel param in Connect same as channel_n", "test_4", conf) + + def _callback(message): + test(message[0] == 1, "Publish Successful", "test_4", conf) + + def _error(message): + test(False, "Publish Successful", "test_4", conf) + + pubnub.publish(channel=channel_n, message=message, callback=_callback, error=_error) + + pubnub.subscribe(channels=channel_wc, callback=callback_wc, error=error, connect=connect_wc) + + pubnub.subscribe(channels=channel_n, callback=callback_n, error=error, connect=connect_n) + + pubnub.subscribe_group(channel_groups=[channel_group], callback=callback_group, error=error, + connect=connect_group) + + def _error(message): + test(False, "Channel Group Creation failed") + + pubnub.channel_group_add_channel(channel_group=channel_group, channel=channel_g, callback=_callback, error=_error) + + +pubnub = Pubnub(publish_key="ds", subscribe_key="ds", + secret_key="ds", ssl_on=False) + +pubnub2 = Pubnub(publish_key="ds", subscribe_key="ds", + secret_key="ds", ssl_on=False) + +pubnub_ssl = Pubnub(publish_key="ds", subscribe_key="ds", + secret_key="ds", ssl_on=True) + +pubnub_ssl_2 = Pubnub(publish_key="ds", subscribe_key="ds", + secret_key="ds", ssl_on=True) + +pubnub_enc = Pubnub(publish_key="ds", subscribe_key="ds", + secret_key="ds", cipher_key="enigma", ssl_on=False) + +pubnub_enc_2 = Pubnub(publish_key="ds", subscribe_key="ds", + secret_key="ds", cipher_key="enigma", ssl_on=False, daemon=False) + +pubnub_enc_ssl = Pubnub(publish_key="ds", subscribe_key="ds", + secret_key="ds", cipher_key="enigma", ssl_on=False) + +pubnub_enc_ssl_2 = Pubnub(publish_key="ds", subscribe_key="ds", + secret_key="ds", cipher_key="enigma", ssl_on=False, daemon=False) + +# run_tests([ ("[EMOJI][ENC]", test_4, pubnub_enc, pubnub_enc_2, "😀")]) + + +run_tests([ + ("", test_1, pubnub, pubnub2), + ("[SSL]", test_1, pubnub_ssl, pubnub_ssl_2), + ("[ENC]", test_1, pubnub_enc, pubnub_enc_2), + ("[SSL][ENC]", test_1, pubnub_enc_ssl, pubnub_enc_ssl_2), + ("", test_2, pubnub, pubnub2), + ("[SSL]", test_2, pubnub_ssl, pubnub_ssl_2), + ("[ENC]", test_2, pubnub_enc, pubnub_enc_2), + ("[SSL][ENC]", test_2, pubnub_enc_ssl, pubnub_enc_ssl_2), + ("", test_3, pubnub, pubnub2), + ("[SSL]", test_3, pubnub_ssl, pubnub_ssl_2), + ("[ENC]", test_3, pubnub_enc, pubnub_enc_2), + ("[SSL][ENC]", test_3, pubnub_enc_ssl, pubnub_enc_ssl_2), + ("", test_3, pubnub, pubnub2), + ("[SSL]", test_3, pubnub_ssl, pubnub_ssl_2), + ("[ENC]", test_3, pubnub_enc, pubnub_enc_2), + ("[SSL][ENC]", test_3, pubnub_enc_ssl, pubnub_enc_ssl_2), + ("", test_4, pubnub, pubnub2), + ("[SSL]", test_4, pubnub_ssl, pubnub_ssl_2), + ("[ENC]", test_4, pubnub_enc, pubnub_enc_2), + ("[SSL][ENC]", test_4, pubnub_enc_ssl, pubnub_enc_ssl_2), + ("[EMOJI]", test_1, pubnub, pubnub2, "😀"), + ("[SSL][EMOJI]", test_1, pubnub_ssl, pubnub_ssl_2, "😀"), + ("[ENC][EMOJI]", test_1, pubnub_enc, pubnub_enc_2, "😀"), + ("[SSL][ENC][EMOJI]", test_1, pubnub_enc_ssl, pubnub_enc_ssl_2, "😀"), + ("[EMOJI]", test_2, pubnub, pubnub2, "😀"), + ("[SSL][EMOJI]", test_2, pubnub_ssl, pubnub_ssl_2, "😀"), + ("[ENC][EMOJI]", test_2, pubnub_enc, pubnub_enc_2, "😀"), + ("[SSL][ENC][EMOJI]", test_2, pubnub_enc_ssl, pubnub_enc_ssl_2, "😀"), + ("[EMOJI]", test_3, pubnub, pubnub2, "😀"), + ("[SSL][EMOJI]", test_3, pubnub_ssl, pubnub_ssl_2, "😀"), + ("[ENC][EMOJI]", test_3, pubnub_enc, pubnub_enc_2, "😀"), + ("[SSL][ENC][EMOJI]", test_3, pubnub_enc_ssl, pubnub_enc_ssl_2, "😀"), + ("[EMOJI]", test_3, pubnub, pubnub2, "😀"), + ("[SSL][EMOJI]", test_3, pubnub_ssl, pubnub_ssl_2, "😀"), + ("[ENC][EMOJI]", test_3, pubnub_enc, pubnub_enc_2, "😀"), + ("[SSL][ENC][EMOJI]", test_3, pubnub_enc_ssl, pubnub_enc_ssl_2, "😀"), + ("[EMOJI]", test_3, pubnub, pubnub2, "😀"), + ("[SSL][EMOJI]", test_3, pubnub_ssl, pubnub_ssl_2, "😀"), + ("[ENC][EMOJI]", test_3, pubnub_enc, pubnub_enc_2, "😀"), + ("[SSL][ENC][EMOJI]", test_3, pubnub_enc_ssl, pubnub_enc_ssl_2, "😀"), + ("[EMOJI]", test_4, pubnub, pubnub2, "😀"), + ("[SSL][EMOJI]", test_4, pubnub_ssl, pubnub_ssl_2, "😀"), + ("[ENC][EMOJI]", test_4, pubnub_enc, pubnub_enc_2, "😀"), + ("[SSL][ENC][EMOJI]", test_4, pubnub_enc_ssl, pubnub_enc_ssl_2, "😀") +])