def main(): pnconfig = PNConfiguration() pnconfig.subscribe_key = os.environ['PUBNUB_SUBSCRIBE_KEY'] pnconfig.ssl = False pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels(os.environ['PUBNUB_CHANNELS'].split(':')).execute()
def test_subscribe_unsubscribe(self): pubnub = PubNub(pnconf_sub_copy()) ch = helper.gen_channel("test-subscribe-sub-unsub") try: listener = SubscribeListener() pubnub.add_listener(listener) pubnub.subscribe().channels(ch).execute() assert ch in pubnub.get_subscribed_channels() assert len(pubnub.get_subscribed_channels()) == 1 listener.wait_for_connect() assert ch in pubnub.get_subscribed_channels() assert len(pubnub.get_subscribed_channels()) == 1 pubnub.unsubscribe().channels(ch).execute() assert ch not in pubnub.get_subscribed_channels() assert len(pubnub.get_subscribed_channels()) == 0 listener.wait_for_disconnect() assert ch not in pubnub.get_subscribed_channels() assert len(pubnub.get_subscribed_channels()) == 0 except PubNubException as e: self.fail(e) finally: pubnub.stop()
class PubSub(): """ Handles the publish/subscribe layer of the application. Provides the communcation between the nodes of the blockchain network. """ def __init__(self, blockchain, transaction_pool): self.pubnub = PubNub(pnconfig) self.pubnub.subscribe().channels(CHANNELS.values()).execute() self.pubnub.add_listener(Listener(blockchain, transaction_pool)) def publish(self, channel, message): """ Publish the message object to the channel. """ self.pubnub.publish().channel(channel).message(message).sync() def broadcast_block(self, block): """ Broadcast a block object to all nodes. """ self.publish(CHANNELS['BLOCK'], block.to_json()) def broadcast_transaction(self, transaction): """ Broadcast a transaction to all nodes. """ self.publish(CHANNELS['TRANSACTION'], transaction.to_json())
def main(_): pnconfig = PNConfiguration() pnconfig.publish_key = 'pub-c-ef4b6aa1-d5ca-43f8-92c8-f9840fb5bb9f' pnconfig.subscribe_key = 'sub-c-151a8936-0fc7-11e8-941f-7e2964818bdb' pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels(CHANNEL).execute()
def test_subscribe_cg_join_leave(self): ch = helper.gen_channel("test-subscribe-unsubscribe-channel") gr = helper.gen_channel("test-subscribe-unsubscribe-group") pubnub = PubNub(pnconf_sub_copy()) pubnub_listener = PubNub(pnconf_sub_copy()) non_subscribe_listener = NonSubscribeListener() pubnub.add_channel_to_channel_group() \ .channel_group(gr) \ .channels(ch) \ .async(non_subscribe_listener.callback) result = non_subscribe_listener.await_result_and_reset() assert isinstance(result, PNChannelGroupsAddChannelResult) time.sleep(1) callback_messages = SubscribeListener() callback_presence = SubscribeListener() pubnub_listener.add_listener(callback_presence) pubnub_listener.subscribe().channel_groups(gr).with_presence().execute() callback_presence.wait_for_connect() prs_envelope = callback_presence.wait_for_presence_on(ch) assert prs_envelope.event == 'join' assert prs_envelope.uuid == pubnub_listener.uuid assert prs_envelope.channel == ch assert prs_envelope.subscription == gr pubnub.add_listener(callback_messages) pubnub.subscribe().channel_groups(gr).execute() prs_envelope = callback_presence.wait_for_presence_on(ch) assert prs_envelope.event == 'join' assert prs_envelope.uuid == pubnub.uuid assert prs_envelope.channel == ch assert prs_envelope.subscription == gr pubnub.unsubscribe().channel_groups(gr).execute() prs_envelope = callback_presence.wait_for_presence_on(ch) assert prs_envelope.event == 'leave' assert prs_envelope.uuid == pubnub.uuid assert prs_envelope.channel == ch assert prs_envelope.subscription == gr pubnub_listener.unsubscribe().channel_groups(gr).execute() callback_presence.wait_for_disconnect() pubnub.remove_channel_from_channel_group() \ .channel_group(gr) \ .channels(ch) \ .async(non_subscribe_listener.callback) result = non_subscribe_listener.await_result_and_reset() assert isinstance(result, PNChannelGroupsRemoveChannelResult) pubnub.stop() pubnub_listener.stop()
class PubSub(): """ Handles the publish/subscribe layer of the application. Provides communication between the nodes of the blockchain network. """ def __init__(self, blockchain): self.pubnub = PubNub(pnconfig) self.pubnub.subscribe().channels(CHANNELS.values()).execute() self.pubnub.add_listener(Listener(blockchain)) def publish(self, channel, message): """ Publish the message object to the channel. """ self.pubnub.publish().channel(channel).message(message).sync() def broadcast_block(self, block): """ Broadcast a block object to all nodes. """ self.publish(CHANNELS['BLOCK'], block.to_json()) # def main(): # pubsub = PubSub() # # time.sleep(1) # # pubsub.publish(CHANNELS['TEST'], { 'foo': 'bar' }) # if __name__ == '__main__': # main()
class PubSub(): """ Handles the publish layer of the app Provides community between then nodes of the blockchain network Obsługuje warstwę publikowania aplikacji Zapewnia społeczność między następnie węzłami sieci blockchain """ def __init__(self, blockchain, transactionPool): self.pubnub = PubNub(pnconfig) self.pubnub.subscribe().channels(Channels.values()).execute() self.pubnub.add_listener(Listener(blockchain, transactionPool)) def publish(self, channel, msg): """ Publish the msg obj to the channel """ self.pubnub.publish().channel(channel).message(msg).sync() def broadcastBlock(self, block): """ Broadcast a block obj to all nodes """ self.publish(Channels['BLOCK'], block.to_json()) def broadcastTransaction(self, transaction): """ Broadcast transaction to all nodes """ self.publish(Channels['TRANSACTION'], transaction.to_json())
class PubSub(): """ Handles the publish and subscribe layer of the application Provides the communication between the ndoes of the blockchain network """ def __init__(self, blockchain): self.pubnub = PubNub(pnconfig) # Tells that pubnub is now subscribed to all designated channels self.pubnub.subscribe().channels(CHANNELS.values()).execute() # Deals with what happens when packet received self.pubnub.add_listener(Listener(blockchain)) def publish(self, channel, message): """ Publish the message to the channel. """ self.pubnub.publish().channel(channel).message(message).sync() def broadcast_block(self, block): """ Broadcast a block object to all nodes. """ self.publish(CHANNELS['BLOCK'], block.to_json())
class PubSub(): """ Handles the publisher/subscriber layer of the application it prvides the communication b/w the nhe nodes of the network """ def __init__(self, blockchain, transaction_pool): self.pubnub = PubNub(pnconfig) #This function causes the client to create an open TCP socket to the PubNub Real-Time self.pubnub.subscribe().channels(CHANNELS.values()).execute() self.pubnub.add_listener(Listener(blockchain, transaction_pool)) def publish(self, channel, message): """ publish the message object to the channel """ self.pubnub.publish().channel(channel).message(message).sync() def broadcast_block(self, block): """ Broadcast a block object to all nodes """ self.publish(CHANNELS['BLOCK'], block.to_json()) def broadcast_transaction(self, transaction): """ Broadcast a transaction to all nodes """ self.publish(CHANNELS['TRANSACTION'], transaction.to_json())
def get_setup_pubnub(): class SubCallback(SubscribeCallback): def presence(self, pubnub, presence): pass def status(self, pubnub, status): pass def message(self, pubnub, message): message_dict = message.message request_id = uuid.UUID(message_dict["request_id"]) response_rebuilder[request_id].append(message_dict) deduped = deduped_chunks(response_rebuilder[request_id]) if len(deduped) == message_dict["chunks"]: deduped.sort(key=lambda item: item["chunk_index"], ) response_content = base64.urlsafe_b64decode( str("".join([d["response_content"] for d in deduped]))) request_pool[request_id] = response_content del response_rebuilder[request_id] pnconfig = PNConfiguration() pnconfig.subscribe_key = SUBSCRIBE_KEY pnconfig.publish_key = PUBLISH_KEY pnconfig.ssl = False pubnub = PubNub(pnconfig) callback = SubCallback() pubnub.add_listener(callback) pubnub.subscribe().channels('channelRX').execute() # pubnub.unsubscribe_all() # pubnub.stop() return pubnub
class PubSub(): ''' Handles the publish/Subscribe layer of application Provides communication bw nodes of a blockchain network ''' def __init__(self, blockchain, transaction_pool): self.pubnub = PubNub(pnconfig) self.pubnub.subscribe().channels(CHANNELS.values()).execute( ) # Sends a request to online pubnub application that this object is now subscribed to this channel self.pubnub.add_listener(Listener(blockchain, transaction_pool)) def publish(self, channel, message): self.pubnub.publish().channel(channel).message( message).sync() # Send the message to all subscribers def broadcast_block(self, block): ''' Broadcast a block object to all nodes ''' self.publish(CHANNELS['BLOCK'], block.to_json()) def broadcast_transaction(self, transaction): """ Broadcast a transaction to all nodes. """ self.publish(CHANNELS['TRANSACTION'], transaction.to_json())
def get(self, request): pnconfig = PNConfiguration() pnconfig.subscribe_key = "sub-c-c7c2aa20-b56f-11e8-b6ef-c2e67adadb66" pnconfig.publish_key = "pub-c-fdd957cd-be31-427f-9e91-9c2bed852ba9" pnconfig.ssl = True pubnub = PubNub(pnconfig) my_listener = SubscribeListener() pubnub.add_listener(my_listener) pubnub.subscribe().channels("test_channel").execute() my_listener.wait_for_connect() print('connected') pubnub.publish().channel('test_channel').message({ 'order': 16, 'owner': 1 }).sync() info = my_listener.wait_for_message_on('test_channel') print(info.message) print(pubnub.time()) print(pubnub.timestamp()) pubnub.unsubscribe().channels('test_channel').execute() my_listener.wait_for_disconnect() print('unsubscribe') envelope = pubnub.history().channel('test_channel').count(100).sync() print(envelope) return Response(dict(info.message))
class PubSub(): """ This section, handles the publish/subscribe layer of the application. It provides the communication between the nodes of the blockchain network. """ def __init__(self, blockchain, transaction_pool): self.pubnub = PubNub(pncofig) self.pubnub.subscribe().channels( COMMUNICATION_CHANNELS.values()).execute() self.pubnub.add_listener(Listener(blockchain, transaction_pool)) def publish(self, channel, message): """ This section is for publishing the message object to the channel """ self.pubnub.publish().channel(channel).message(message).sync() def block_broadcast(self, block): """ This section takes care of broacasting a block object to all noeds """ self.publish(COMMUNICATION_CHANNELS['BLOCK'], block.convert_block_to_json()) def broadcast_transaction(self, transaction): """ Broadcast a transaction to all nodes. """ self.publish(COMMUNICATION_CHANNELS['TRANSACTION'], transaction.convert_transaction_data_to_json())
def test_subscribe_unsubscribe(self): pubnub = PubNub(pnconf_sub_copy()) ch = helper.gen_channel("test-subscribe-sub-unsub") try: listener = SubscribeListener() pubnub.add_listener(listener) pubnub.subscribe().channels(ch).execute() assert ch in pubnub.get_subscribed_channels() assert len(pubnub.get_subscribed_channels()) == 1 listener.wait_for_connect() assert ch in pubnub.get_subscribed_channels() assert len(pubnub.get_subscribed_channels()) == 1 pubnub.unsubscribe().channels(ch).execute() assert ch not in pubnub.get_subscribed_channels() assert len(pubnub.get_subscribed_channels()) == 0 listener.wait_for_disconnect() assert ch not in pubnub.get_subscribed_channels() assert len(pubnub.get_subscribed_channels()) == 0 except PubNubException as e: self.fail(e) finally: pubnub.stop()
def _subscribe(self, pnconfig, channels): listener = JobCompleteListener(self._check_message, self._poll_and_set_api_result) pubnub = PubNub(pnconfig) pubnub.add_listener(listener) pubnub.subscribe().channels(channels).execute() return pubnub
def test_cg_subscribe_unsubscribe(self): ch = helper.gen_channel("test-subscribe-unsubscribe-channel") gr = helper.gen_channel("test-subscribe-unsubscribe-group") pubnub = PubNub(pnconf_sub_copy()) callback_messages = SubscribeListener() cg_operation = NonSubscribeListener() pubnub.add_channel_to_channel_group()\ .channel_group(gr)\ .channels(ch)\ .async(cg_operation.callback) result = cg_operation.await_result() assert isinstance(result, PNChannelGroupsAddChannelResult) cg_operation.reset() time.sleep(1) pubnub.add_listener(callback_messages) pubnub.subscribe().channel_groups(gr).execute() callback_messages.wait_for_connect() pubnub.unsubscribe().channel_groups(gr).execute() callback_messages.wait_for_disconnect() pubnub.remove_channel_from_channel_group()\ .channel_group(gr)\ .channels(ch)\ .async(cg_operation.callback) result = cg_operation.await_result() assert isinstance(result, PNChannelGroupsRemoveChannelResult) pubnub.stop()
class PubNubHandler: def __init__(self): self.pnconfig = PNConfiguration() self.pnconfig.subscribe_key = 'sub-c-ec33873a-53d1-11e8-84ad-b20235bcb09b' self.pnconfig.publish_key = 'pub-c-56bfd71d-e6e9-479d-9c08-b2c719d6a4c7' self.pnconfig.secret_key = 'sec-c-OWY1ZDU0NGUtN2IyZC00YmJmLWFmNTEtOTc3NDFkYWE0YjUw' self.pubnub = PubNub(self.pnconfig) self.my_channels = [ 'all-roads', 'update-congestion', 'fire-in-progress', 'update-position', 'fire-extinguished' ] self.connected = False self.Subscribe() def Subscribe(self): callback = SCSubscribeCallback() self.pubnub.add_listener(callback) self.pubnub.subscribe().channels(self.my_channels).execute() while not callback.subscribed: if callback.failed: break self.connected = callback.subscribed def Publish(self, message, channel): if self.connected: if self.pubnub.publish().channel(channel).message(message).async(my_publish_callback): print("pubbed %s to %s" % message, channel) else:
def test_subscribe_pub_unsubscribe(self): ch = helper.gen_channel("test-subscribe-sub-pub-unsub") pubnub = PubNub(pnconf_sub_copy()) subscribe_listener = SubscribeListener() publish_operation = NonSubscribeListener() message = "hey" try: pubnub.add_listener(subscribe_listener) pubnub.subscribe().channels(ch).execute() subscribe_listener.wait_for_connect() pubnub.publish().channel(ch).message(message).pn_async( publish_operation.callback) if publish_operation. await () is False: self.fail("Publish operation timeout") publish_result = publish_operation.result assert isinstance(publish_result, PNPublishResult) assert publish_result.timetoken > 0 result = subscribe_listener.wait_for_message_on(ch) assert isinstance(result, PNMessageResult) assert result.channel == ch assert result.subscription is None assert result.timetoken > 0 assert result.message == message pubnub.unsubscribe().channels(ch).execute() subscribe_listener.wait_for_disconnect()
def main(): print("***************************************************") print(f"* Listening to channel {CHANNEL}") print("***************************************************") pubnub = PubNub(PN_CONFIG) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels(CHANNEL).with_presence().execute()
def test_cg_subscribe_unsubscribe(self): ch = helper.gen_channel("test-subscribe-unsubscribe-channel") gr = helper.gen_channel("test-subscribe-unsubscribe-group") pubnub = PubNub(pnconf_sub_copy()) callback_messages = SubscribeListener() cg_operation = NonSubscribeListener() pubnub.add_channel_to_channel_group()\ .channel_group(gr)\ .channels(ch)\ .pn_async(cg_operation.callback) result = cg_operation.await_result() assert isinstance(result, PNChannelGroupsAddChannelResult) cg_operation.reset() time.sleep(1) pubnub.add_listener(callback_messages) pubnub.subscribe().channel_groups(gr).execute() callback_messages.wait_for_connect() pubnub.unsubscribe().channel_groups(gr).execute() callback_messages.wait_for_disconnect() pubnub.remove_channel_from_channel_group()\ .channel_group(gr)\ .channels(ch)\ .pn_async(cg_operation.callback) result = cg_operation.await_result() assert isinstance(result, PNChannelGroupsRemoveChannelResult) pubnub.stop()
class PubSub(): """ Manages the publish/subscribe layer of the application, affording scalable communications infrastructure across nodes. """ def __init__(self, blockchain, transaction_pool): self.pubnub = PubNub(pnconfig) self.pubnub.subscribe().channels(CHANNELS.values()).execute() self.pubnub.add_listener(Listener(blockchain, transaction_pool)) def publish(self, channel_str, message_obj): """ Publish given message obj to given channel. """ self.pubnub.publish().channel(channel_str).message(message_obj).sync() def broadcast_block(self, block): """ Broadcast a block obj to all nodes. """ self.publish(CHANNELS["BLOCK"], block.serialize_to_json()) def broadcast_transaction(self, transaction): """ Broadcast a transaction obj to all nodes. """ self.publish(CHANNELS['TRANSACTION'], transaction.serialize_to_json())
def test_subscribe_pub_unsubscribe(self): ch = helper.gen_channel("test-subscribe-sub-pub-unsub") pubnub = PubNub(pnconf_sub_copy()) subscribe_listener = SubscribeListener() publish_operation = NonSubscribeListener() message = "hey" try: pubnub.add_listener(subscribe_listener) pubnub.subscribe().channels(ch).execute() subscribe_listener.wait_for_connect() pubnub.publish().channel(ch).message(message).async(publish_operation.callback) if publish_operation.await() is False: self.fail("Publish operation timeout") publish_result = publish_operation.result assert isinstance(publish_result, PNPublishResult) assert publish_result.timetoken > 0 result = subscribe_listener.wait_for_message_on(ch) assert isinstance(result, PNMessageResult) assert result.channel == ch assert result.subscription is None assert result.timetoken > 0 assert result.message == message pubnub.unsubscribe().channels(ch).execute() subscribe_listener.wait_for_disconnect()
class PubSub(): """ Class to handle publish/subscribe from PubNub. Used to communicate between different blockchain peers. """ def __init__(self, blockchain, transaction_pool): #initialize the pubnub object self.pubnub = PubNub(pnconfig) #subscribe to the channels that we need to listen to and receive data self.pubnub.subscribe().channels(CHANNELS.values()).execute() #add the listener to listen for incoming block data self.pubnub.add_listener(Listener(blockchain, transaction_pool)) def publish(self, message, channel): """ Method to publish a message via a channel """ self.pubnub.publish().channel(channel).message(message).sync() def broadcast_block(self, block): """ Method to broadcast the block in the form of JSON to all peers. """ self.publish(block.to_json(), CHANNELS['BLOCK']) def broadcast_transaction(self, transaction): """ Method to broadcast the block in the form of JSON to all peers. """ self.publish(transaction.to_json(), CHANNELS['TRANSACTIONS'])
class PubSub(): def __init__(self): self.pubnub = PubNub(pnconfig) self.pubnub.subscribe().channels([TEST_CHANNEL]).execute() self.pubnub.add_listener(Listener()) def publish(self, channel, message): self.pubnub.publish().channel(channel).message(message).sync()
def init_pubnub(): global pubnub pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-fc4f4ea8-e4cb-11e7-ab5b-be68b02b0975' pnconfig.publish_key = 'pub-c-b7e0c189-0969-4105-857a-9fdf1466e1ee' pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('magicmirror').execute() print('pubnub subscription completed')
class PubNubClient: display_controller = None # PubNub configurations class NewMessageSubscribeCallback(SubscribeCallback): def __init__(self, firebase_client, drecorder, display_controller): self.firebase_client = firebase_client # self._drecorder = drecorder self.display_controller = display_controller def status(self, pubnub, status): pass def presence(self, pubnub, presence): pprint(presence.__dict__) def message(self, pubnub, message): print('\n') print('message from pubnub received') print('\n') if message.__dict__["message"]["content"] == "message_uploaded": # self.display_controller.stop_loading() num_messages = self.firebase_client.num_relevant_recordings() self.display_controller.display_message_counter(num_messages) # if message.__dict__["message"]["sender"] == pnconfig.uuid: # pass # self._firebase_client.fetch_relevant_recordings() def __init__(self, firebase_client, drecorder, display_controller): self.pubnub = PubNub(pnconfig) self.pubnub.add_listener( self.NewMessageSubscribeCallback(firebase_client, drecorder, display_controller)) self.pubnub.subscribe()\ .channels("pubnub_onboarding_channel")\ .with_presence()\ .execute() # self.firebase_client = firebase_client self.drecorder = drecorder self.display_controller = display_controller def publish_callback(self, envelope, status): # print('full circle') print('\n') print('pubnub message published') print('\n') # print(envelope, status) def broadcastUploadedMessage(self): self.pubnub.publish()\ .channel("pubnub_onboarding_channel")\ .message({"sender": pnconfig.uuid, "content": EVENT_UPLOADED_MESSAGE, "url": self.drecorder.firebase_filename})\ .pn_async(self.publish_callback)
def init_pubnub(): global pubnub pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-f97a2b14-b03f-11e7-8d4b-66b981d3b880' pnconfig.publish_key = 'pub-c-b7f324ac-e190-4bcf-ba5e-b860168f6f9b' pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('magicmirror').execute() print ('pubnub subscription completed')
def init_pubnub(): global pubnub pnconfig = PNConfiguration() pnconfig.subscribe_key = 'SUBSCRIBE_KEY' pnconfig.publish_key = 'PUBLISH_KEY' pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('magicmirror').execute() print('pubnub subscription completed')
def init_pubnub(): global pubnub pnconfig = PNConfiguration() pnconfig.subscribe_key = 'pub-c-bc8de339-f4af-48fb-ad34-dce0abdc9531' pnconfig.publish_key = 'pub-c-bc8de339-f4af-48fb-ad34-dce0abdc9531' pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('magicmirror').execute() print('pubnub subscription completed')
def init_chatroom(nickname): pnconfig = PNConfiguration() pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pnconfig.publish_key = pubkey pnconfig.subscribe_key = subkey pnconfig.uuid = nickname pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('mychatroom').with_presence().execute() return pubnub
def init_pubnub(): global pubnub pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-c6f57af0-4134-11e8-afae-2a65d00afee8' pnconfig.publish_key = 'pub-c-0cc9b82a-4cd0-4a90-9ab3-7705e5a07575' pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('magicmirror').execute() print ('pubnub subscription completed')
def init_pubnub(): global pubnub pnconfig = PNConfiguration() pnconfig.subscribe_key = cfg.api['subscribe_key'] pnconfig.publish_key = cfg.api['publish_key'] pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('magicmirror').execute() print ('pubnub subscription completed')
def subscribe(channels, keys): print('subscribing now... {c}, {k}'.format(c=channels, k=keys)) pnconfig = PNConfiguration() pnconfig.subscribe_key = keys[0] pnconfig.publish_key = keys[1] pnconfig.secret_key = keys[2] pubnub = PubNub(pnconfig) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels(channels).execute()
class PubSub(): def __init__(self,blockchain,transaction_pool): self.pubnub=PubNub(pnconfig) self.pubnub.subscribe().channels(CHANNELS.values()).execute() self.pubnub.add_listener(Listener(blockchain,transaction_pool)) def publish(self,channel,message): self.pubnub.publish().channel(channel).message(message).sync() def broadcast_block(self,block): self.publish(CHANNELS['BLOCK'],block.to_json()) def broadcast_transaction(self,transaction): self.publish(CHANNELS['TRANSACTION'],transaction.to_json())
def test_timeout_event_on_broken_heartbeat(self): ch = helper.gen_channel("heartbeat-test") pubnub = PubNub(messenger_config) pubnub_listener = PubNub(listener_config) pubnub.config.uuid = helper.gen_channel("messenger") pubnub_listener.config.uuid = helper.gen_channel("listener") callback_presence = SubscribeListener() callback_messages = SubscribeListener() # - connect to :ch-pnpres pubnub_listener.add_listener(callback_presence) pubnub_listener.subscribe().channels(ch).with_presence().execute() callback_presence.wait_for_connect() presence_message = callback_presence.wait_for_presence_on(ch) assert ch == presence_message.channel assert 'join' == presence_message.event assert pubnub_listener.uuid == presence_message.uuid # - connect to :ch pubnub.add_listener(callback_messages) pubnub.subscribe().channels(ch).execute() callback_messages.wait_for_connect() prs_envelope = callback_presence.wait_for_presence_on(ch) assert ch == prs_envelope.channel assert 'join' == prs_envelope.event assert pubnub.uuid == prs_envelope.uuid # wait for one heartbeat call time.sleep(6) # - break messenger heartbeat loop pubnub._subscription_manager._stop_heartbeat_timer() # - assert for timeout presence_message = callback_presence.wait_for_presence_on(ch) assert ch == presence_message.channel assert 'timeout' == presence_message.event assert pubnub.uuid == presence_message.uuid pubnub.unsubscribe().channels(ch).execute() callback_messages.wait_for_disconnect() # - disconnect from :ch-pnpres pubnub_listener.unsubscribe().channels(ch).execute() callback_presence.wait_for_disconnect() pubnub.stop() pubnub_listener.stop()
def test_join_leave(self): ch = helper.gen_channel("test-subscribe-join-leave") pubnub = PubNub(pnconf_sub_copy()) pubnub_listener = PubNub(pnconf_sub_copy()) callback_messages = SubscribeListener() callback_presence = SubscribeListener() pubnub.config.uuid = helper.gen_channel("messenger") pubnub_listener.config.uuid = helper.gen_channel("listener") try: pubnub.add_listener(callback_messages) pubnub_listener.add_listener(callback_presence) pubnub_listener.subscribe().channels(ch).with_presence().execute() callback_presence.wait_for_connect() envelope = callback_presence.wait_for_presence_on(ch) assert envelope.channel == ch assert envelope.event == 'join' assert envelope.uuid == pubnub_listener.uuid pubnub.subscribe().channels(ch).execute() callback_messages.wait_for_connect() envelope = callback_presence.wait_for_presence_on(ch) assert envelope.channel == ch assert envelope.event == 'join' assert envelope.uuid == pubnub.uuid pubnub.unsubscribe().channels(ch).execute() callback_messages.wait_for_disconnect() envelope = callback_presence.wait_for_presence_on(ch) assert envelope.channel == ch assert envelope.event == 'leave' assert envelope.uuid == pubnub.uuid pubnub_listener.unsubscribe().channels(ch).execute() callback_presence.wait_for_disconnect() except PubNubException as e: self.fail(e) finally: pubnub.stop() pubnub_listener.stop()
def test_subscribe_cg_publish_unsubscribe(self): ch = helper.gen_channel("test-subscribe-unsubscribe-channel") gr = helper.gen_channel("test-subscribe-unsubscribe-group") message = "hey" pubnub = PubNub(pnconf_sub_copy()) callback_messages = SubscribeListener() non_subscribe_listener = NonSubscribeListener() pubnub.add_channel_to_channel_group() \ .channel_group(gr) \ .channels(ch) \ .async(non_subscribe_listener.callback) result = non_subscribe_listener.await_result_and_reset() assert isinstance(result, PNChannelGroupsAddChannelResult) time.sleep(1) pubnub.add_listener(callback_messages) pubnub.subscribe().channel_groups(gr).execute() callback_messages.wait_for_connect() pubnub.publish().message(message).channel(ch).async(non_subscribe_listener.callback) result = non_subscribe_listener.await_result_and_reset() assert isinstance(result, PNPublishResult) assert result.timetoken > 0 pubnub.unsubscribe().channel_groups(gr).execute() callback_messages.wait_for_disconnect() pubnub.remove_channel_from_channel_group() \ .channel_group(gr) \ .channels(ch) \ .async(non_subscribe_listener.callback) result = non_subscribe_listener.await_result_and_reset() assert isinstance(result, PNChannelGroupsRemoveChannelResult) pubnub.stop()
kafka_hosts = args.kafka print("Writing to kafka ...") print(my_topic) producer = KafkaProducer(bootstrap_servers=kafka_hosts) push_to_kafka = True if args.debug: PRINT_TERM = True else: PRINT_TERM = False except: print("Printing to console. Will not write to kafka.") PRINT_TERM = True if PRINT_TERM: print("Print pubnub events to terminal.") else: print("Will not print events to terminal.") # bootstrap the config object pnconf = PNConfiguration() PUBNUB_SUBSCRIBE_KEY = stream_info['sub_key'] CHANNEL = stream_info['channel'] pnconf.subscribe_key = PUBNUB_SUBSCRIBE_KEY pnconf.ssl = False # create the pub / sub client pubnub = PubNub(pnconf) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels(CHANNEL).execute()
class MySubscribeCallback(SubscribeCallback): def status(self, pubnub, status): print("### status changed to: %s" % status.category) if status.category == PNStatusCategory.PNReconnectedCategory: pubnub.stop() def message(self, pubnub, message): pass def presence(self, pubnub, presence): pass pnconf = PNConfiguration() pnconf.publish_key = "demo" pnconf.subscribe_key = "demo" pnconf.origin = "localhost:8089" pnconf.subscribe_request_timeout = 10 pnconf.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNub(pnconf) time_until_open_again = 8 my_listener = MySubscribeCallback() pubnub.add_listener(my_listener) pubnub.subscribe().channels('my_channel').execute() # atexit.register(pubnub.stop)