aboutsummaryrefslogtreecommitdiffstats
path: root/python-twisted
diff options
context:
space:
mode:
Diffstat (limited to 'python-twisted')
-rw-r--r--python-twisted/Pubnub.py487
-rw-r--r--python-twisted/Pubnub.pycbin0 -> 12246 bytes
-rw-r--r--python-twisted/PubnubCrypto.py92
-rw-r--r--python-twisted/PubnubCrypto.pycbin0 -> 2619 bytes
-rw-r--r--python-twisted/README118
-rw-r--r--python-twisted/examples/history-example.py44
-rw-r--r--python-twisted/examples/publish-example.py60
-rw-r--r--python-twisted/examples/subscribe-example.py50
-rw-r--r--python-twisted/examples/uuid-example.py28
-rw-r--r--python-twisted/tests/benchmark.py87
-rw-r--r--python-twisted/tests/delivery.py162
-rw-r--r--python-twisted/tests/unit-test-full.py224
-rw-r--r--python-twisted/tests/unit-test.py107
13 files changed, 1459 insertions, 0 deletions
diff --git a/python-twisted/Pubnub.py b/python-twisted/Pubnub.py
new file mode 100644
index 0000000..3c3f4b1
--- /dev/null
+++ b/python-twisted/Pubnub.py
@@ -0,0 +1,487 @@
+## www.pubnub.com - PubNub Real-time push service in the cloud.
+# coding=utf8
+
+## PubNub Real-time Push APIs and Notifications Framework
+## Copyright (c) 2010 Stephen Blum
+## http://www.pubnub.com/
+
+## -----------------------------------
+## PubNub 3.1 Real-time Push Cloud API
+## -----------------------------------
+import sys
+import json
+import time
+import hashlib
+import urllib2
+import uuid
+try:
+ from hashlib import sha256
+ digestmod = sha256
+except ImportError:
+ import Crypto.Hash.SHA256 as digestmod
+ sha256 = digestmod.new
+import hmac
+from twisted.internet import reactor
+from twisted.internet.defer import Deferred
+from twisted.internet.protocol import Protocol
+from twisted.web.client import Agent
+from twisted.web.client import HTTPConnectionPool
+from twisted.web.http_headers import Headers
+from PubnubCrypto import PubnubCrypto
+import gzip
+import zlib
+
+pnconn_pool = HTTPConnectionPool(reactor)
+pnconn_pool.maxPersistentPerHost = 100
+pnconn_pool.cachedConnectionTimeout = 310
+
+class Pubnub():
+
+ def start(self): reactor.run()
+ def stop(self): reactor.stop()
+ def timeout( self, callback, delay ):
+ reactor.callLater( delay, callback )
+
+ def __init__(
+ self,
+ publish_key,
+ subscribe_key,
+ secret_key = False,
+ cipher_key = False,
+ ssl_on = False,
+ origin = 'pubsub.pubnub.com'
+ ) :
+ """
+ #**
+ #* Pubnub
+ #*
+ #* Init the Pubnub Client API
+ #*
+ #* @param string publish_key required key to send messages.
+ #* @param string subscribe_key required key to receive messages.
+ #* @param string secret_key required key to sign messages.
+ #* @param boolean ssl required for 2048 bit encrypted messages.
+ #* @param string origin PUBNUB Server Origin.
+ #**
+
+ ## Initiat Class
+ pubnub = Pubnub( 'PUBLISH-KEY', 'SUBSCRIBE-KEY', 'SECRET-KEY', False )
+
+ """
+ self.origin = origin
+ self.publish_key = publish_key
+ self.subscribe_key = subscribe_key
+ self.secret_key = secret_key
+ self.cipher_key = cipher_key
+ self.ssl = ssl_on
+ self.subscriptions = {}
+
+ if self.ssl :
+ self.origin = 'https://' + self.origin
+ else :
+ self.origin = 'http://' + self.origin
+
+
+ def publish( self, args ) :
+ """
+ #**
+ #* Publish
+ #*
+ #* Send a message to a channel.
+ #*
+ #* @param array args with channel and message.
+ #* @return array success information.
+ #**
+
+ ## Publish Example
+ def publish_complete(info):
+ print(info)
+
+ pubnub.publish({
+ 'channel' : 'hello_world',
+ 'message' : {
+ 'some_text' : 'Hello my World'
+ },
+ 'callback' : publish_complete
+ })
+
+ """
+ ## Capture Callback
+ if args.has_key('callback'): callback = args['callback']
+ else: callback = lambda x : x
+
+ ## Fail if bad input.
+ if not (args['channel'] and args['message']):
+ callback([ 0, 'Missing Channel or Message', 0 ])
+ return False
+
+ ## Capture User Input
+ channel = str(args['channel'])
+ message = args['message']
+
+ if self.cipher_key :
+ pc = PubnubCrypto()
+ out = []
+ if type( message ) == type(list()):
+ for item in message:
+ encryptItem = pc.encrypt(self.cipher_key, item ).rstrip()
+ out.append(encryptItem)
+ message = json.dumps(out)
+ elif type( message ) == type(dict()):
+ outdict = {}
+ for k, item in message.iteritems():
+ encryptItem = pc.encrypt(self.cipher_key, item ).rstrip()
+ outdict[k] = encryptItem
+ out.append(outdict)
+ message = json.dumps(out[0])
+ else:
+ message = json.dumps(pc.encrypt(self.cipher_key, message).replace('\n',''))
+ else :
+ message = json.dumps(args['message'])
+
+ def publish_response(info):
+ callback(info or [0, 'Disconnected', 0]);
+
+ ## Sign Message
+ if self.secret_key :
+ hashObject = sha256()
+ hashObject.update(self.secret_key)
+ hashedSecret = hashObject.hexdigest()
+ hash = hmac.HMAC(hashedSecret, '/'.join([
+ self.publish_key,
+ self.subscribe_key,
+ self.secret_key,
+ channel,
+ message
+ ]), digestmod=digestmod)
+ signature = hash.hexdigest()
+ else :
+ signature = '0'
+
+ ## Send Message
+ return self._request([
+ 'publish',
+ self.publish_key,
+ self.subscribe_key,
+ signature,
+ channel,
+ '0',
+ message
+ ], publish_response )
+
+
+ def subscribe( self, args ) :
+ """
+ #**
+ #* Subscribe
+ #*
+ #* This is NON-BLOCKING.
+ #* Listen for a message on a channel.
+ #*
+ #* @param array args with channel and message.
+ #* @return false on fail, array on success.
+ #**
+
+ ## Subscribe Example
+ def receive(message) :
+ print(message)
+ return True
+
+ ## On Connect Callback
+ def connected() :
+ pubnub.publish({
+ 'channel' : 'hello_world',
+ 'message' : { 'some_var' : 'text' }
+ })
+
+ ## Subscribe
+ pubnub.subscribe({
+ 'channel' : 'hello_world',
+ 'connect' : connected,
+ 'callback' : receive
+ })
+
+ """
+ ## Fail if missing channel
+ if not 'channel' in args :
+ return 'Missing Channel.'
+
+ ## Fail if missing callback
+ if not 'callback' in args :
+ return 'Missing Callback.'
+
+ ## Capture User Input
+ channel = str(args['channel'])
+ callback = args['callback']
+ connectcb = args['connect']
+
+ if 'errorback' in args:
+ errorback = args['errorback']
+ else:
+ errorback = lambda x: x
+
+ ## New Channel?
+ if not (channel in self.subscriptions) :
+ self.subscriptions[channel] = {
+ 'first' : False,
+ 'connected' : 0,
+ 'timetoken' : '0'
+ }
+
+ ## Ensure Single Connection
+ if self.subscriptions[channel]['connected'] :
+ return "Already Connected"
+
+ self.subscriptions[channel]['connected'] = 1
+
+ ## SUBSCRIPTION RECURSION
+ def substabizel():
+ ## STOP CONNECTION?
+ if not self.subscriptions[channel]['connected']:
+ return
+
+ def sub_callback(response):
+ ## STOP CONNECTION?
+ if not self.subscriptions[channel]['connected']:
+ return
+
+ ## CONNECTED CALLBACK
+ if not self.subscriptions[channel]['first'] :
+ self.subscriptions[channel]['first'] = True
+ connectcb()
+
+ ## PROBLEM?
+ if not response:
+ def time_callback(_time):
+ if not _time:
+ reactor.callLater( 1, substabizel )
+ return errorback("Lost Network Connection")
+ else:
+ reactor.callLater( 1, substabizel )
+
+ ## ENSURE CONNECTED (Call Time Function)
+ return self.time({ 'callback' : time_callback })
+
+ self.subscriptions[channel]['timetoken'] = response[1]
+ substabizel()
+
+ pc = PubnubCrypto()
+ out = []
+ for message in response[0]:
+ if self.cipher_key :
+ if type( message ) == type(list()):
+ for item in message:
+ encryptItem = pc.decrypt(self.cipher_key, item )
+ out.append(encryptItem)
+ message = out
+ elif type( message ) == type(dict()):
+ outdict = {}
+ for k, item in message.iteritems():
+ encryptItem = pc.decrypt(self.cipher_key, item )
+ outdict[k] = encryptItem
+ out.append(outdict)
+ message = out[0]
+ else:
+ message = pc.decrypt(self.cipher_key, message )
+ else :
+ message
+
+ callback(message)
+
+ ## CONNECT TO PUBNUB SUBSCRIBE SERVERS
+ try :
+ self._request( [
+ 'subscribe',
+ self.subscribe_key,
+ channel,
+ '0',
+ str(self.subscriptions[channel]['timetoken'])
+ ], sub_callback )
+ except :
+ reactor.callLater( 1, substabizel )
+ return
+
+ ## BEGIN SUBSCRIPTION (LISTEN FOR MESSAGES)
+ substabizel()
+
+
+ def unsubscribe( self, args ):
+ channel = str(args['channel'])
+ if not (channel in self.subscriptions):
+ return False
+
+ ## DISCONNECT
+ self.subscriptions[channel]['connected'] = 0
+ self.subscriptions[channel]['timetoken'] = 0
+ self.subscriptions[channel]['first'] = False
+
+
+ def history( self, args ) :
+ """
+ #**
+ #* History
+ #*
+ #* Load history from a channel.
+ #*
+ #* @param array args with 'channel' and 'limit'.
+ #* @return mixed false on fail, array on success.
+ #*
+
+ ## History Example
+ history = pubnub.history({
+ 'channel' : 'hello_world',
+ 'limit' : 1
+ })
+ print(history)
+
+ """
+ ## Capture User Input
+ limit = args.has_key('limit') and int(args['limit']) or 10
+ channel = str(args['channel'])
+
+ ## Fail if bad input.
+ if not channel :
+ return 'Missing Channel'
+
+ ## Get History
+ pc = PubnubCrypto()
+ return self._request( [
+ 'history',
+ self.subscribe_key,
+ channel,
+ '0',
+ str(limit)
+ ], args['callback'] )
+
+ def time( self, args ) :
+ """
+ #**
+ #* Time
+ #*
+ #* Timestamp from PubNub Cloud.
+ #*
+ #* @return int timestamp.
+ #*
+
+ ## PubNub Server Time Example
+ def time_complete(timestamp):
+ print(timestamp)
+
+ pubnub.time(time_complete)
+
+ """
+ def complete(response) :
+ if not response: return 0
+ args['callback'](response[0])
+
+ self._request( [
+ 'time',
+ '0'
+ ], complete )
+
+ def uuid(self) :
+ """
+ #**
+ #* uuid
+ #*
+ #* Generate a UUID
+ #*
+ #* @return UUID.
+ #*
+
+ ## PubNub UUID Example
+ uuid = pubnub.uuid()
+ print(uuid)
+ """
+ return uuid.uuid1()
+
+ def _request( self, request, callback ) :
+ global pnconn_pool
+
+ ## Build URL
+ url = self.origin + '/' + "/".join([
+ "".join([ ' ~`!@#$%^&*()+=[]\\{}|;\':",./<>?'.find(ch) > -1 and
+ hex(ord(ch)).replace( '0x', '%' ).upper() or
+ ch for ch in list(bit)
+ ]) for bit in request])
+
+ requestType = request[0]
+ agent = Agent(
+ reactor,
+ self.ssl and None or pnconn_pool,
+ connectTimeout=30
+ )
+ request = agent.request( 'GET', url, Headers({
+ 'V' : ['3.1'],
+ 'User-Agent' : ['Python-Twisted'],
+ 'Accept-Encoding' : ['gzip']
+ }), None )
+
+ self.resulting_is = str()
+ def received(response):
+ headerlist = list(response.headers.getAllRawHeaders())
+ for item in headerlist:
+ if( item[0] == "Content-Encoding"):
+ if type(item[1]) == type(list()):
+ for subitem in item[1]:
+ self.resulting_is = subitem
+ elif type(item[1]) == type(str()):
+ self.resulting_is = item[1]
+
+ finished = Deferred()
+ response.deliverBody(PubNubResponse(finished))
+ return finished
+
+ def complete(data):
+ if ( type(data) == type(str()) ):
+ if self.resulting_is:
+ d = zlib.decompressobj(16+zlib.MAX_WBITS)
+
+ try : data = d.decompress(data) # try/catch here, pass through if except
+ except : data = data
+
+ try : obj = json.loads(data)
+ except : obj = None
+
+ pc = PubnubCrypto()
+ out = []
+ if self.cipher_key :
+ if requestType == "history" :
+ if type(obj) == type(list()):
+ for item in obj:
+ if type(item) == type(list()):
+ for subitem in item:
+ encryptItem = pc.decrypt(self.cipher_key, subitem )
+ out.append(encryptItem)
+ elif type(item) == type(dict()):
+ outdict = {}
+ for k, subitem in item.iteritems():
+ encryptItem = pc.decrypt(self.cipher_key, subitem )
+ outdict[k] = encryptItem
+ out.append(outdict)
+ else :
+ encryptItem = pc.decrypt(self.cipher_key, item )
+ out.append(encryptItem)
+ callback(out)
+ elif type( obj ) == type(dict()):
+ for k, item in obj.iteritems():
+ encryptItem = pc.decrypt(self.cipher_key, item )
+ out.append(encryptItem)
+ callback(out)
+ else :
+ callback(obj)
+ else :
+ callback(obj)
+
+ request.addCallback(received)
+ request.addBoth(complete)
+
+
+
+class PubNubResponse(Protocol):
+ def __init__( self, finished ):
+ self.finished = finished
+
+ def dataReceived( self, bytes ):
+ self.finished.callback(bytes)
+
diff --git a/python-twisted/Pubnub.pyc b/python-twisted/Pubnub.pyc
new file mode 100644
index 0000000..94d6ecc
--- /dev/null
+++ b/python-twisted/Pubnub.pyc
Binary files differ
diff --git a/python-twisted/PubnubCrypto.py b/python-twisted/PubnubCrypto.py
new file mode 100644
index 0000000..744f2d3
--- /dev/null
+++ b/python-twisted/PubnubCrypto.py
@@ -0,0 +1,92 @@
+## www.pubnub.com - PubNub Real-time push service in the cloud.
+# coding=utf8
+
+## PubNub Real-time Push APIs and Notifications Framework
+## Copyright (c) 2010 Stephen Blum
+## http://www.pubnub.com/
+
+## -----------------------------------
+## PubNub 3.1 Real-time Push Cloud API
+## -----------------------------------
+
+from Crypto.Cipher import AES
+from Crypto.Hash import MD5
+from base64 import encodestring, decodestring
+import hashlib
+import hmac
+
+class PubnubCrypto() :
+ """
+ #**
+ #* PubnubCrypto
+ #*
+ #**
+
+ ## Initiate Class
+ pc = PubnubCrypto
+
+ """
+
+ def pad( self, msg, block_size=16 ):
+ """
+ #**
+ #* pad
+ #*
+ #* pad the text to be encrypted
+ #* appends a padding character to the end of the String
+ #* until the string has block_size length
+ #* @return msg with padding.
+ #**
+ """
+ return msg + ((block_size - len(msg) % block_size) * chr(block_size - len(msg) % block_size))
+
+ def depad( self, msg ):
+ """
+ #**
+ #* depad
+ #*
+ #* depad the decryptet message"
+ #* @return msg without padding.
+ #**
+ """
+ return msg[0:-ord(msg[-1])]
+
+ def getSecret( self, key ):
+ """
+ #**
+ #* getSecret
+ #*
+ #* hases the key to MD5
+ #* @return key in MD5 format
+ #**
+ """
+ return MD5.new(key).digest()
+
+ def encrypt( self, key, msg ):
+ """
+ #**
+ #* encrypt
+ #*
+ #* encrypts the message
+ #* @return message in encrypted format
+ #**
+ """
+ secret = self.getSecret(key)
+ Initial16bytes='0123456789012345'
+ cipher = AES.new(secret,AES.MODE_CBC,Initial16bytes)
+ return encodestring(cipher.encrypt(self.pad(msg)))
+
+ def decrypt( self, key, msg ):
+ """
+ #**
+ #* decrypt
+ #*
+ #* decrypts the message
+ #* @return message in decryped format
+ #**
+ """
+ secret = self.getSecret(key)
+ Initial16bytes='0123456789012345'
+ cipher = AES.new(secret,AES.MODE_CBC,Initial16bytes)
+ return self.depad((cipher.decrypt(decodestring(msg))))
+
diff --git a/python-twisted/PubnubCrypto.pyc b/python-twisted/PubnubCrypto.pyc
new file mode 100644
index 0000000..a349424
--- /dev/null
+++ b/python-twisted/PubnubCrypto.pyc
Binary files differ
diff --git a/python-twisted/README b/python-twisted/README
new file mode 100644
index 0000000..5f9b350
--- /dev/null
+++ b/python-twisted/README
@@ -0,0 +1,118 @@
+## ---------------------------------------------------
+##
+## YOU MUST HAVE A PUBNUB ACCOUNT TO USE THE API.
+## http://www.pubnub.com/account
+##
+## ----------------------------------------------------
+
+## ----------------------------------------------------
+## PubNub 3.1 Real-time Cloud Push API - PYTHON TWISTED
+## ----------------------------------------------------
+##
+## www.pubnub.com - PubNub Real-time Push Service in the Cloud.
+## http://github.com/pubnub/pubnub-api/tree/master/python-twisted/
+##
+## PubNub is a Massively Scalable Real-time Service for Web and Mobile Games.
+## This is a cloud-based service for broadcasting Real-time messages
+## to thousands of web and mobile clients simultaneously.
+
+## ----------------------------------------------------
+## Python Twisted Setup
+## ----------------------------------------------------
+## Download BZ2 archive from http://twistedmatrix.com/
+##
+## > tar xvfj Twisted-12.1.0.tar.bz2
+## > cd Twisted-12.1.0
+## > sudo python setup.py install
+##
+
+## ----------------------------------------------------
+## Third Party Libraries Dependency
+## ----------------------------------------------------
+## You must download and install,
+##
+## 1. pyopenssl
+## Download from https://launchpad.net/pyopenssl
+##
+## 2. pycrypto
+## Download from https://github.com/dlitz/pycrypto OR
+## from http://code.google.com/p/uploadprj/downloads/detail?name=pycrypto-2.3.win32-py2.7.zip&can=2&q
+
+## ---------------
+## Python Push API
+## ---------------
+pubnub = Pubnub(
+ "demo", ## PUBLISH_KEY
+ "demo", ## SUBSCRIBE_KEY
+ "demo", ## SECRET_KEY
+ "", ## CIPHER_KEY (Cipher key is Optional)
+ False ## SSL_ON?
+)
+
+## -----------------------------------------------------------------------
+## IO Event Loop
+## -----------------------------------------------------------------------
+## VERY IMPORTANT TO ADD THIS LINE AT THE VERY BOTTOM!
+##
+## reactor.run() ## IMPORTANT!
+##
+
+## -----------------------------------------------------------------------
+## Subscribe Example
+## -----------------------------------------------------------------------
+
+def connected() :
+ ## -----------------------------------------------------------------------
+ ## Publish Example
+ ## -----------------------------------------------------------------------
+ def publish_complete(info):
+ print(info)
+
+ pubnub.publish({
+ 'channel' : "my-twisted-channel",
+ 'message' : {
+ 'some_text' : 'Hello World!'
+ },
+ 'callback' : publish_complete
+ })
+
+def message_received(message):
+ print(message)
+
+pubnub.subscribe({
+ 'channel' : "my-twisted-channel",
+ 'connect' : connected,
+ 'callback' : message_received
+})
+
+## -----------------------------------------------------------------------
+## Time Example
+## -----------------------------------------------------------------------
+def time_complete(timestamp):
+ print(timestamp)
+
+pubnub.time({ 'callback' : time_complete })
+
+## -----------------------------------------------------------------------
+## History Example
+## -----------------------------------------------------------------------
+def history_complete(messages):
+ print(messages)
+
+pubnub.history( {
+ 'channel' : "my-twisted-channel",
+ 'limit' : 10,
+ 'callback' : history_complete
+})
+
+## -----------------------------------------------------------------------
+## UUID Example
+## -----------------------------------------------------------------------
+uuid = pubnub.uuid()
+print "UUID"
+print uuid
+
+## -----------------------------------------------------------------------
+## IO Event Loop
+## -----------------------------------------------------------------------
+reactor.run()
diff --git a/python-twisted/examples/history-example.py b/python-twisted/examples/history-example.py
new file mode 100644
index 0000000..31b8edb
--- /dev/null
+++ b/python-twisted/examples/history-example.py
@@ -0,0 +1,44 @@
+## www.pubnub.com - PubNub Real-time push service in the cloud.
+# coding=utf8
+
+## PubNub Real-time Push APIs and Notifications Framework
+## Copyright (c) 2010 Stephen Blum
+## http://www.pubnub.com/
+
+## -----------------------------------
+## PubNub 3.1 Real-time Push Cloud API
+## -----------------------------------
+
+import sys
+from twisted.internet import reactor
+sys.path.append('../')
+from Pubnub import Pubnub
+
+publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'
+subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo'
+secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo'
+cipher_key = len(sys.argv) > 4 and sys.argv[4] or ''
+ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False
+
+## -----------------------------------------------------------------------
+## Initiate Pubnub State
+## -----------------------------------------------------------------------
+pubnub = Pubnub( publish_key, subscribe_key, secret_key, cipher_key, ssl_on )
+crazy = 'hello_world'
+
+## -----------------------------------------------------------------------
+## History Example
+## -----------------------------------------------------------------------
+def history_complete(messages):
+ print(messages)
+
+pubnub.history( {
+ 'channel' : crazy,
+ 'limit' : 10,
+ 'callback' : history_complete
+})
+
+## -----------------------------------------------------------------------
+## IO Event Loop
+## -----------------------------------------------------------------------
+reactor.run()
diff --git a/python-twisted/examples/publish-example.py b/python-twisted/examples/publish-example.py
new file mode 100644
index 0000000..4a5baf6
--- /dev/null
+++ b/python-twisted/examples/publish-example.py
@@ -0,0 +1,60 @@
+## www.pubnub.com - PubNub Real-time push service in the cloud.
+# coding=utf8
+
+## PubNub Real-time Push APIs and Notifications Framework
+## Copyright (c) 2010 Stephen Blum
+## http://www.pubnub.com/
+
+## -----------------------------------
+## PubNub 3.1 Real-time Push Cloud API
+## -----------------------------------
+
+import sys
+from twisted.internet import reactor
+sys.path.append('../')
+from Pubnub import Pubnub
+
+publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'
+subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo'
+secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo'
+cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' ##(Cipher key is Optional)
+ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False
+
+## -----------------------------------------------------------------------
+## Initiate Pubnub State
+## -----------------------------------------------------------------------
+pubnub = Pubnub( publish_key, subscribe_key, secret_key, cipher_key, ssl_on )
+crazy = 'hello_world'
+
+## -----------------------------------------------------------------------
+## Publish Example
+## -----------------------------------------------------------------------
+def publish_complete(info):
+ print(info)
+
+## Publish string
+pubnub.publish({
+ 'channel' : crazy,
+ 'message' : 'Hello World!',
+ 'callback' : publish_complete
+})
+
+## Publish list
+li = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
+pubnub.publish({
+ 'channel' : crazy,
+ 'message' : li,
+ 'callback' : publish_complete
+})
+
+## Publish Dictionary Object
+pubnub.publish({
+ 'channel' : crazy,
+ 'message' : { 'some_key' : 'some_val' },
+ 'callback' : publish_complete
+})
+
+## -----------------------------------------------------------------------
+## IO Event Loop
+## -----------------------------------------------------------------------
+reactor.run()
diff --git a/python-twisted/examples/subscribe-example.py b/python-twisted/examples/subscribe-example.py
new file mode 100644
index 0000000..994e7e3
--- /dev/null
+++ b/python-twisted/examples/subscribe-example.py
@@ -0,0 +1,50 @@
+## www.pubnub.com - PubNub Real-time push service in the cloud.
+# coding=utf8
+
+## PubNub Real-time Push APIs and Notifications Framework
+## Copyright (c) 2010 Stephen Blum
+## http://www.pubnub.com/
+
+## -----------------------------------
+## PubNub 3.1 Real-time Push Cloud API
+## -----------------------------------
+
+import sys
+from twisted.internet import reactor
+sys.path.append('../')
+from Pubnub import Pubnub
+
+publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'
+subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo'
+secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo'
+cipher_key = len(sys.argv) > 4 and sys.argv[4] or None
+ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False
+
+## -----------------------------------------------------------------------
+## Initiate Pubnub State
+## -----------------------------------------------------------------------
+pubnub = Pubnub( publish_key, subscribe_key, secret_key, cipher_key, ssl_on )
+crazy = 'hello_world'
+
+## -----------------------------------------------------------------------
+## Subscribe Example
+## -----------------------------------------------------------------------
+def message_received(message):
+ print(message)
+
+def connected() :
+ pubnub.publish({
+ 'channel' : crazy,
+ 'message' : { 'Info' : 'Connected!' }
+ })
+
+pubnub.subscribe({
+ 'channel' : crazy,
+ 'connect' : connected,
+ 'callback' : message_received
+})
+
+## -----------------------------------------------------------------------
+## IO Event Loop
+## -----------------------------------------------------------------------
+reactor.run()
diff --git a/python-twisted/examples/uuid-example.py b/python-twisted/examples/uuid-example.py
new file mode 100644
index 0000000..94840e0
--- /dev/null
+++ b/python-twisted/examples/uuid-example.py
@@ -0,0 +1,28 @@
+## www.pubnub.com - PubNub Real-time push service in the cloud.
+# coding=utf8
+
+## PubNub Real-time Push APIs and Notifications Framework
+## Copyright (c) 2010 Stephen Blum
+## http://www.pubnub.com/
+
+## -----------------------------------
+## PubNub 3.1 Real-time Push Cloud API
+## -----------------------------------
+
+import sys
+from twisted.internet import reactor
+sys.path.append('../')
+from Pubnub import Pubnub
+
+## -----------------------------------------------------------------------
+## Initiate Pubnub State
+## -----------------------------------------------------------------------
+pubnub = Pubnub( "", "", "", False )
+
+## -----------------------------------------------------------------------
+## UUID Example
+## -----------------------------------------------------------------------
+
+uuid = pubnub.uuid()
+print "UUID: "
+print uuid
diff --git a/python-twisted/tests/benchmark.py b/python-twisted/tests/benchmark.py
new file mode 100644
index 0000000..d4d6d80
--- /dev/null
+++ b/python-twisted/tests/benchmark.py
@@ -0,0 +1,87 @@
+## www.pubnub.com - PubNub Real-time push service in the cloud.
+# coding=utf8
+
+## PubNub Real-time Push APIs and Notifications Framework
+## Copyright (c) 2010 Stephen Blum
+## http://www.pubnub.com/
+
+## -----------------------------------
+## PubNub 3.0 Real-time Push Cloud API
+## -----------------------------------
+
+import sys
+import datetime
+from twisted.internet import reactor
+sys.path.append('../')
+from Pubnub import Pubnub
+
+publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'
+subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo'
+secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo'
+cipher_key = len(sys.argv) > 4 and sys.argv[4] or 'demo'
+ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False
+
+## -----------------------------------------------------------------------
+## Initiat Class
+## -----------------------------------------------------------------------
+pubnub = Pubnub( publish_key, subscribe_key, secret_key, cipher_key, ssl_on )
+crazy = ' ~`!@#$%^&*( 顶顅 Ȓ)+=[]\\{}|;\':",./<>?abcd'
+
+## -----------------------------------------------------------------------
+## BENCHMARK
+## -----------------------------------------------------------------------
+def connected() :
+ pubnub.publish({
+ 'channel' : crazy,
+ 'message' : { 'Info' : 'Connected!' }
+ })
+
+trips = { 'last' : None, 'current' : None, 'max' : 0, 'avg' : 0 }
+
+def received(message):
+ current_trip = trips['current'] = str(datetime.datetime.now())[0:19]
+ last_trip = trips['last'] = str(
+ datetime.datetime.now() - datetime.timedelta(seconds=1)
+ )[0:19]
+
+ ## New Trip Span (1 Second)
+ if not trips.has_key(current_trip) :
+ trips[current_trip] = 0
+
+ ## Average
+ if trips.has_key(last_trip):
+ trips['avg'] = (trips['avg'] + trips[last_trip]) / 2
+
+ ## Increment Trip Counter
+ trips[current_trip] = trips[current_trip] + 1
+
+ ## Update Max
+ if trips[current_trip] > trips['max'] :
+ trips['max'] = trips[current_trip]
+
+
+ print(message)
+
+ pubnub.publish({
+ 'channel' : crazy,
+ 'message' : current_trip +
+ " Trip: " +
+ str(trips[current_trip]) +
+ " MAX: " +
+ str(trips['max']) +
+ "/sec " +
+ " AVG: " +
+ str(trips['avg']) +
+ "/sec"
+ })
+
+pubnub.subscribe({
+ 'channel' : crazy,
+ 'connect' : connected,
+ 'callback' : received
+})
+
+## -----------------------------------------------------------------------
+## IO Event Loop
+## -----------------------------------------------------------------------
+reactor.run()
diff --git a/python-twisted/tests/delivery.py b/python-twisted/tests/delivery.py
new file mode 100644
index 0000000..dc6b9e2
--- /dev/null
+++ b/python-twisted/tests/delivery.py
@@ -0,0 +1,162 @@
+## www.pubnub.com - PubNub Real-time push service in the cloud.
+# coding=utf8
+
+## PubNub Real-time Push APIs and Notifications Framework
+## Copyright (c) 2010 Stephen Blum
+## http://www.pubnub.com/
+
+## -----------------------------------
+## PubNub 3.1 Real-time Push Cloud API
+## -----------------------------------
+
+import sys
+import datetime
+import time
+import math
+
+sys.path.append('../')
+from Pubnub import Pubnub
+
+## -----------------------------------------------------------------------
+## Configuration
+## -----------------------------------------------------------------------
+publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'
+subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo'
+secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo'
+cipher_key = len(sys.argv) > 4 and sys.argv[4] or 'demo'
+ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False
+origin = len(sys.argv) > 6 and sys.argv[6] or 'pubsub.pubnub.com'
+origin = '184.72.9.220'
+
+## -----------------------------------------------------------------------
+## Analytics
+## -----------------------------------------------------------------------
+analytics = {
+ 'publishes' : 0, ## Total Send Requests
+ 'received' : 0, ## Total Received Messages (Deliveries)
+ 'queued' : 0, ## Total Unreceived Queue (UnDeliveries)
+ 'successful_publishes' : 0, ## Confirmed Successful Publish Request
+ 'failed_publishes' : 0, ## Confirmed UNSuccessful Publish Request
+ 'failed_deliveries' : 0, ## (successful_publishes - received)
+ 'deliverability' : 0 ## Percentage Delivery
+}
+
+trips = {
+ 'last' : None,
+ 'current' : None,
+ 'max' : 0,
+ 'avg' : 0
+}
+
+## -----------------------------------------------------------------------
+## Initiat Class
+## -----------------------------------------------------------------------
+channel = 'deliverability-' + str(time.time())
+pubnub = Pubnub(
+ publish_key,
+ subscribe_key,
+ secret_key = secret_key,
+ cipher_key = cipher_key,
+ ssl_on = ssl_on,
+ origin = origin
+)
+
+## -----------------------------------------------------------------------
+## BENCHMARK
+## -----------------------------------------------------------------------
+def publish_sent(info = None):
+ if info and info[0]: analytics['successful_publishes'] += 1
+ else: analytics['failed_publishes'] += 1
+
+ analytics['publishes'] += 1
+ analytics['queued'] += 1
+
+ pubnub.timeout( send, 0.1 )
+
+def send():
+ if analytics['queued'] > 100:
+ analytics['queued'] -= 10
+ return pubnub.timeout( send, 10 )
+
+ pubnub.publish({
+ 'channel' : channel,
+ 'callback' : publish_sent,
+ 'message' : "1234567890"
+ })
+
+def received(message):
+ analytics['queued'] -= 1
+ analytics['received'] += 1
+ current_trip = trips['current'] = str(datetime.datetime.now())[0:19]
+ last_trip = trips['last'] = str(
+ datetime.datetime.now() - datetime.timedelta(seconds=1)
+ )[0:19]
+
+ ## New Trip Span (1 Second)
+ if not trips.has_key(current_trip) :
+ trips[current_trip] = 0
+
+ ## Average
+ if trips.has_key(last_trip):
+ trips['avg'] = (trips['avg'] + trips[last_trip]) / 2
+
+ ## Increment Trip Counter
+ trips[current_trip] = trips[current_trip] + 1
+
+ ## Update Max
+ if trips[current_trip] > trips['max'] :
+ trips['max'] = trips[current_trip]
+
+def show_status():
+ ## Update Failed Deliveries
+ analytics['failed_deliveries'] = \
+ analytics['successful_publishes'] \
+ - analytics['received']
+
+ ## Update Deliverability
+ analytics['deliverability'] = (
+ float(analytics['received']) / \
+ float(analytics['successful_publishes'] or 1.0)
+ ) * 100.0
+
+ ## Print Display
+ print( (
+ "max:%(max)03d/sec " + \
+ "avg:%(avg)03d/sec " + \
+ "pubs:%(publishes)05d " + \
+ "received:%(received)05d " + \
+ "spub:%(successful_publishes)05d " + \
+ "fpub:%(failed_publishes)05d " + \
+ "failed:%(failed_deliveries)05d " + \
+ "queued:%(queued)03d " + \
+ "delivery:%(deliverability)03f%% " + \
+ ""
+ ) % {
+ 'max' : trips['max'],
+ 'avg' : trips['avg'],
+ 'publishes' : analytics['publishes'],
+ 'received' : analytics['received'],
+ 'successful_publishes' : analytics['successful_publishes'],
+ 'failed_publishes' : analytics['failed_publishes'],
+ 'failed_deliveries' : analytics['failed_deliveries'],
+ 'publishes' : analytics['publishes'],
+ 'deliverability' : analytics['deliverability'],
+ 'queued' : analytics['queued']
+ } )
+ pubnub.timeout( show_status, 1 )
+
+def connected():
+ show_status()
+ pubnub.timeout( send, 1 )
+
+print( "Connected: %s\n" % origin )
+pubnub.subscribe({
+ 'channel' : channel,
+ 'connect' : connected,
+ 'callback' : received
+})
+
+## -----------------------------------------------------------------------
+## IO Event Loop
+## -----------------------------------------------------------------------
+pubnub.start()
diff --git a/python-twisted/tests/unit-test-full.py b/python-twisted/tests/unit-test-full.py
new file mode 100644
index 0000000..f593d11
--- /dev/null
+++ b/python-twisted/tests/unit-test-full.py
@@ -0,0 +1,224 @@
+## www.pubnub.com - PubNub Real-time push service in the cloud.
+# coding=utf8
+
+## PubNub Real-time Push APIs and Notifications Framework
+## Copyright (c) 2010 Stephen Blum
+## http://www.pubnub.com/
+
+## TODO Tests
+##
+## - wait 20 minutes, send a message, receive and success.
+## -
+## -
+##
+##
+
+## -----------------------------------
+## PubNub 3.1 Real-time Push Cloud API
+## -----------------------------------
+
+import sys
+sys.path.append('../')
+from Pubnub import Pubnub
+
+publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'
+subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo'
+secret_key = len(sys.argv) > 3 and sys.argv[3] or None
+cipher_key = len(sys.argv) > 4 and sys.argv[4] or None
+ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False
+
+## -----------------------------------------------------------------------
+## Command Line Options Supplied PubNub
+## -----------------------------------------------------------------------
+pubnub_user_supplied_options = Pubnub(
+ publish_key, ## OPTIONAL (supply None to disable)
+ subscribe_key, ## REQUIRED
+ secret_key, ## OPTIONAL (supply None to disable)
+ cipher_key, ## OPTIONAL (supply None to disable)
+ ssl_on ## OPTIONAL (supply None to disable)
+)
+
+## -----------------------------------------------------------------------
+## High Security PubNub
+## -----------------------------------------------------------------------
+pubnub_high_security = Pubnub(
+ ## Publish Key
+ 'pub-c-a30c030e-9f9c-408d-be89-d70b336ca7a0',
+
+ ## Subscribe Key
+ 'sub-c-387c90f3-c018-11e1-98c9-a5220e0555fd',
+
+ ## Secret Key
+ 'sec-c-MTliNDE0NTAtYjY4Ni00MDRkLTllYTItNDhiZGE0N2JlYzBl',
+
+ ## Cipher Key
+ 'YWxzamRmbVjFaa05HVnGFqZHM3NXRBS73jxmhVMkjiwVVXV1d5UrXR1JLSkZFRr'+
+ 'WVd4emFtUm1iR0TFpUZvbiBoYXMgYmVlbxWkhNaF3uUi8kM0YkJTEVlZYVFjBYi'+
+ 'jFkWFIxSkxTa1pGUjd874hjklaTFpUwRVuIFNob3VsZCB5UwRkxUR1J6YVhlQWa'+
+ 'V1ZkNGVH32mDkdho3pqtRnRVbTFpUjBaeGUgYXNrZWQtZFoKjda40ZWlyYWl1eX'+
+ 'U4RkNtdmNub2l1dHE2TTA1jd84jkdJTbFJXYkZwWlZtRnKkWVrSRhhWbFpZVmFz'+
+ 'c2RkZmTFpUpGa1dGSXhTa3hUYTFwR1Vpkm9yIGluZm9ybWFNfdsWQdSiiYXNWVX'+
+ 'RSblJWYlRGcFVqQmFlRmRyYUU0MFpXbHlZV2wxZVhVNFJrTnR51YjJsMWRIRTJU'+
+ 'W91ciBpbmZvcm1hdGliBzdWJtaXR0ZWQb3UZSBhIHJlc3BvbnNlLCB3ZWxsIHJl'+
+ 'VEExWdHVybiB0am0aW9uIb24gYXMgd2UgcG9zc2libHkgY2FuLuhcFe24ldWVns'+
+ 'dSaTFpU3hVUjFKNllWaFdhRmxZUWpCaQo34gcmVxdWlGFzIHNveqQl83snBfVl3',
+
+ ## 2048bit SSL ON - ENABLED TRUE
+ True
+)
+
+## -----------------------------------------------------------------------
+## Channel | Message Test Data (UTF-8)
+## -----------------------------------------------------------------------
+crazy = ' ~`â¦â§!@#$%^&*(顶顅Ȓ)+=[]\\{}|;\':",./<>?abcd'
+many_channels = [ str(x) + '-many_channel_test' for x in range(10) ]
+runthroughs = 0
+planned_tests = 2
+delivery_retries = 0
+max_retries = 10
+
+## -----------------------------------------------------------------------
+## Unit Test Function
+## -----------------------------------------------------------------------
+def test( trial, name ) :
+ if trial : print( 'PASS: ' + name )
+ else : print( '- FAIL - ' + name )
+
+def test_pubnub(pubnub):
+ global runthroughs, planned_tests, delivery_retries, max_retries
+
+ ## -----------------------------------------------------------------------
+ ## Many Channels
+ ## -----------------------------------------------------------------------
+ def phase2():
+ status = {
+ 'sent' : 0,
+ 'received' : 0,
+ 'connections' : 0
+ }
+
+ def received( message, chan ):
+ global runthroughs
+
+ test( status['received'] <= status['sent'], 'many sends' )
+ status['received'] += 1
+ pubnub.unsubscribe({ 'channel' : chan })
+ if status['received'] == len(many_channels):
+ runthroughs += 1
+ if runthroughs == planned_tests: pubnub.stop()
+
+ def publish_complete( info, chan ):
+ global delivery_retries, max_retries
+ status['sent'] += 1
+ test( info, 'publish complete' )
+ test( info and len(info) > 2, 'publish response' )
+ if not info[0]:
+ delivery_retries += 1
+ if max_retries > delivery_retries: sendit(chan)
+
+ def sendit(chan):
+ tchan = chan
+ pubnub.publish({
+ 'channel' : chan,
+ 'message' : "Hello World",
+ 'callback' : (lambda msg:publish_complete( msg, tchan ))
+ })
+
+ def connected(chan):
+ status['connections'] += 1
+ sendit(chan)
+
+ def delivered(info):
+ if info and info[0]: status['sent'] += 1
+
+ def subscribe(chan):
+ pubnub.subscribe({
+ 'channel' : chan,
+ 'connect' : (lambda:connected(chan+'')),
+ 'callback' : (lambda msg:received( msg, chan ))
+ })
+
+ ## Subscribe All Channels
+ for chan in many_channels: subscribe(chan)
+
+ ## -----------------------------------------------------------------------
+ ## Time Example
+ ## -----------------------------------------------------------------------
+ def time_complete(timetoken):
+ test( timetoken, 'timetoken fetch' )
+ test( isinstance( timetoken, int ), 'timetoken int type' )
+
+ pubnub.time({ 'callback' : time_complete })
+
+ ## -----------------------------------------------------------------------
+ ## Publish Example
+ ## -----------------------------------------------------------------------
+ def publish_complete(info):
+ test( info, 'publish complete' )
+ test( info and len(info) > 2, 'publish response' )
+
+ pubnub.history( {
+ 'channel' : crazy,
+ 'limit' : 10,
+ 'callback' : history_complete
+ })
+
+ ## -----------------------------------------------------------------------
+ ## History Example
+ ## -----------------------------------------------------------------------
+ def history_complete(messages):
+ test( messages and len(messages) > 0, 'history' )
+ test( messages, 'history' )
+
+
+ pubnub.publish({
+ 'channel' : crazy,
+ 'message' : "Hello World",
+ 'callback' : publish_complete
+ })
+
+ ## -----------------------------------------------------------------------
+ ## Subscribe Example
+ ## -----------------------------------------------------------------------
+ def message_received(message):
+ test( message, 'message received' )
+ pubnub.unsubscribe({ 'channel' : crazy })
+
+ def done() :
+ pubnub.unsubscribe({ 'channel' : crazy })
+ pubnub.publish({
+ 'channel' : crazy,
+ 'message' : "Hello World",
+ 'callback' : (lambda x:x)
+ })
+
+ def dumpster(message) :
+ test( 0, 'never see this' )
+
+ pubnub.subscribe({
+ 'channel' : crazy,
+ 'connect' : done,
+ 'callback' : dumpster
+ })
+
+ def connected() :
+ pubnub.publish({
+ 'channel' : crazy,
+ 'message' : { 'Info' : 'Connected!' }
+ })
+
+ pubnub.subscribe({
+ 'channel' : crazy,
+ 'connect' : connected,
+ 'callback' : message_received
+ })
+
+ phase2()
+
+## -----------------------------------------------------------------------
+## Run Tests
+## -----------------------------------------------------------------------
+test_pubnub(pubnub_user_supplied_options)
+test_pubnub(pubnub_high_security)
+pubnub_high_security.start()
+
diff --git a/python-twisted/tests/unit-test.py b/python-twisted/tests/unit-test.py
new file mode 100644
index 0000000..843f939
--- /dev/null
+++ b/python-twisted/tests/unit-test.py
@@ -0,0 +1,107 @@
+## www.pubnub.com - PubNub Real-time push service in the cloud.
+# coding=utf8
+
+## PubNub Real-time Push APIs and Notifications Framework
+## Copyright (c) 2010 Stephen Blum
+## http://www.pubnub.com/
+
+## -----------------------------------
+## PubNub 3.1 Real-time Push Cloud API
+## -----------------------------------
+
+import sys
+sys.path.append('../')
+from Pubnub import Pubnub
+
+publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'
+subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo'
+secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo'
+cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' ##(Cipher key is Optional)
+ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False
+
+## -----------------------------------------------------------------------
+## Initiat Class
+## -----------------------------------------------------------------------
+pubnub = Pubnub( publish_key, subscribe_key, secret_key, cipher_key, ssl_on )
+crazy = ' ~`!@#$%^&*( 顶顅 Ȓ)+=[]\\{}|;\':",./<>?abcd'
+
+## ---------------------------------------------------------------------------
+## Unit Test Function
+## ---------------------------------------------------------------------------
+def test( trial, name ) :
+ if trial :
+ print( 'PASS: ' + name )
+ else :
+ print( 'FAIL: ' + name )
+
+## -----------------------------------------------------------------------
+## Time Example
+## -----------------------------------------------------------------------
+def time_complete(timestamp):
+ print(timestamp)
+
+pubnub.time({ 'callback' : time_complete })
+
+## -----------------------------------------------------------------------
+## History Example
+## -----------------------------------------------------------------------
+def history_complete(messages):
+ print(messages)
+
+pubnub.history( {
+ 'channel' : crazy,
+ 'limit' : 10,
+ 'callback' : history_complete
+})
+
+## -----------------------------------------------------------------------
+## Publish Example
+## -----------------------------------------------------------------------
+def publish_complete(info):
+ print(info)
+
+pubnub.publish({
+ 'channel' : crazy,
+ 'message' : {'one': 'Hello World! --> ɂ顶@#$%^&*()!', 'two': 'hello2'},
+ 'callback' : publish_complete
+})
+
+## -----------------------------------------------------------------------
+## Subscribe Example
+## -----------------------------------------------------------------------
+def message_received(message):
+ print(message)
+ print('Disconnecting...')
+ pubnub.unsubscribe({ 'channel' : crazy })
+
+ def done() :
+ print('final connection, done :)')
+ pubnub.unsubscribe({ 'channel' : crazy })
+ pubnub.stop()
+
+ def dumpster(message) :
+ print('never see this')
+ print(message)
+
+ print('reconnecting...')
+ pubnub.subscribe({
+ 'channel' : crazy,
+ 'connect' : done,
+ 'callback' : dumpster
+ })
+
+def connected() :
+ pubnub.publish({
+ 'channel' : crazy,
+ 'message' : { 'Info' : 'Connected!' }
+ })
+
+pubnub.subscribe({
+ 'channel' : crazy,
+ 'connect' : connected,
+ 'callback' : message_received
+})
+## -----------------------------------------------------------------------
+## IO Event Loop
+## -----------------------------------------------------------------------
+pubnub.start()