Example #1
0
    def __init__(self, delegate):
        self.delegate = delegate

        pubnub.set_stream_logger('pubnub', logging.DEBUG)

        pnconfig = PNConfiguration()
        pnconfig.subscribe_key = "sub-c-d5c0f6b8-f436-11e7-b8a6-46d99af2bb8c"
        pnconfig.publish_key = "pub-c-79775796-e891-4ba0-8e96-af4a5dd71beb"
        pnconfig.ssl = False

        self.pubnub = PubNub(pnconfig)

        self.pubnub.subscribe().channels("create").execute()
        (self.pubnub.subscribe().channels(i).execute()
         for i in range(NUM_CORES))

        self.pubnub.add_listener(self)

        self.async_changed = False
Example #2
0
    async def subscripbe_for_realtime_updates(self) -> None:
        """Subscribes to PubNub for realtime updates."""
        # make a call to vivint's userauth endpoint
        authuser_data = await self.vivintskyapi.get_authuser_data()

        pubnub.set_stream_logger("pubnub", logging.INFO)

        pnconfig = PNConfiguration()
        pnconfig.subscribe_key = PN_SUBSCRIBE_KEY
        pnconfig.ssl = True
        pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR
        pnconfig.heartbeat_notification_options = PNHeartbeatNotificationOptions.ALL

        self.__pubnub = PubNubAsyncio(pnconfig)
        self.__pubnub.add_listener(
            VivintPubNubSubscribeListener(self.handle_pubnub_message)
        )

        pn_channel = f'{PN_CHANNEL}#{authuser_data[AuthUserAttributes.Users][AuthUserAttributes.UsersAttributes.MessageBroadcastChannel]}'  # noqa
        self.__pubnub.subscribe().channels(pn_channel).with_presence().execute()
Example #3
0
    async def subscribe_for_realtime_updates(self, authuser_data: dict = None) -> None:
        """Subscribes to PubNub for realtime updates."""
        # make a call to vivint's authuser endpoint to get message broadcast channel if not supplied
        if not authuser_data:
            authuser_data = await self.vivintskyapi.get_authuser_data()

        pubnub.set_stream_logger("pubnub", logging.INFO)

        pnconfig = PNConfiguration()
        pnconfig.subscribe_key = PN_SUBSCRIBE_KEY
        pnconfig.ssl = True
        pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR
        pnconfig.heartbeat_notification_options = PNHeartbeatNotificationOptions.ALL

        self.__pubnub = PubNubAsyncio(pnconfig)
        self.__pubnub.add_listener(
            VivintPubNubSubscribeListener(self.handle_pubnub_message)
        )

        pn_channel = f"{PN_CHANNEL}#{authuser_data[AuthUserAttribute.USERS][AuthUserAttribute.UserAttribute.MESSAGE_BROADCAST_CHANNEL]}"
        self.__pubnub.subscribe().channels(pn_channel).with_presence().execute()
Example #4
0
        self.pnconfig.publish_key = conf.get("publish_key")
        if self.pnconfig.publish_key is None:
            raise PubSubError("publish key is not configured")
        self.pnconfig.ssl = conf.get("ssl", False)
        self._channels = conf.get("channels")
        self._pubnub = PubNub(self.pnconfig)

    def publish(self, data, meta=None, channels=None):
        # TODO: throttle or queue up messages
        chs = channels or self._channels
        if isinstance(chs, str):
            chs = [chs]
        elif chs is None:
            raise PubSubError("need publish channel")

        for ch in chs:
            p = self._pubnub.publish().channel(ch)
            p.message(data)
            if meta:
                p.meta(meta)
            envelope = p.sync()
            if envelope.status.is_error():
                raise PubSubError("Error publishing to {}: {}".format(
                    ch, envelope.status.error))


if __name__ == "__main__":
    pubnub.set_stream_logger('pubnub', logging.ERROR)
    pubsub = PubSub()
    pubsub.publish({"text": "just published this!"})
import unittest
import logging
import time
import pubnub
import threading

from pubnub.pubnub import PubNub, SubscribeListener, NonSubscribeListener
from tests import helper
from tests.helper import pnconf_sub_copy

pubnub.set_stream_logger('pubnub', logging.DEBUG)


class TestPubNubState(unittest.TestCase):
    def setUp(self):
        self.event = threading.Event()

    def callback(self, response, status):
        self.response = response
        self.status = status
        self.event.set()

    def test_single_channel(self):
        pubnub = PubNub(pnconf_sub_copy())
        ch = helper.gen_channel("wherenow-asyncio-channel")
        uuid = helper.gen_channel("wherenow-asyncio-uuid")
        pubnub.config.uuid = uuid

        subscribe_listener = SubscribeListener()
        where_now_listener = NonSubscribeListener()
        pubnub.add_listener(subscribe_listener)
Example #6
0
import tornado
import logging
import pubnub as pn

from tornado.testing import AsyncTestCase
from pubnub.pubnub_tornado import PubNubTornado
from tests.helper import pnconf_copy
from tests.integrational.tornado.vcr_tornado_decorator import use_cassette_and_stub_time_sleep


pn.set_stream_logger('pubnub', logging.DEBUG)


class TestPubNubState(AsyncTestCase):
    def setUp(self):
        super(TestPubNubState, self).setUp()
        self.pubnub = PubNubTornado(pnconf_copy(), custom_ioloop=self.io_loop)

    @use_cassette_and_stub_time_sleep(
        'tests/integrational/fixtures/tornado/state/single_channel.yaml',
        filter_query_parameters=['uuid', 'seqn', 'pnsdk'],
        match_on=['method', 'host', 'path', 'state_object_in_query'])
    @tornado.testing.gen_test
    def test_state_single_channel(self):
        ch = "state-tornado-ch"
        self.pubnub.config.uuid = 'state-tornado-uuid'
        state = {"name": "Alex", "count": 5}

        env = yield self.pubnub.set_state() \
            .channels(ch) \
            .state(state) \
Example #7
0
# PubNub HereNow usage example
import logging
import os
import sys

d = os.path.dirname
PUBNUB_ROOT = d(d(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(PUBNUB_ROOT)

import pubnub
from examples import pnconf
from pubnub.pubnub import PubNub, NonSubscribeListener

pubnub.set_stream_logger('pubnub', logging.DEBUG, stream=sys.stdout)

pubnub = PubNub(pnconf)

listener = NonSubscribeListener()

pubnub.publish() \
    .channel("blah") \
    .message("hey") \
    .async(listener.callback)

result = listener.await_result_and_reset(5)
# FIX: returns None
print(result)

pubnub.stop()
Example #8
0
import logging

import constants
import settings
from logger import config_logging
from vendored.lirc import Lirc

import pubnub
from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNStatusCategory
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub

logger = config_logging(settings.LOG_LEVEL, settings.LOG_FILE)
pubnub.set_stream_logger('pubnub', logging.WARNING)

pnconfig = PNConfiguration()
pnconfig.subscribe_key = settings.SUBSCRIBE_KEY
pnconfig.publish_key = settings.PUBLISH_KEY
pnconfig.ssl = True

pubnub_client = PubNub(pnconfig)

lirc = Lirc()


class KeyPressSubscribeCallback(SubscribeCallback):
    def presence(self, pubnub, presence):
        pass  # handle incoming presence data
Example #9
0
import asyncio
import pytest
import logging
import pubnub as pn

from pubnub.models.consumer.presence import PNSetStateResult, PNGetStateResult
from pubnub.pubnub_asyncio import PubNubAsyncio
from tests.helper import pnconf, pnconf_copy, pnconf_sub_copy, pnconf_pam_copy
from tests.integrational.vcr_asyncio_sleeper import get_sleeper, VCR599Listener
from tests.integrational.vcr_helper import pn_vcr


pn.set_stream_logger("pubnub", logging.DEBUG)


@pn_vcr.use_cassette(
    "tests/integrational/fixtures/asyncio/state/single_channel.yaml",
    filter_query_parameters=["uuid", "pnsdk"],
    match_on=["method", "host", "path", "state_object_in_query"],
)
@pytest.mark.asyncio
def test_single_channelx(event_loop):
    pubnub = PubNubAsyncio(pnconf_copy(), custom_event_loop=event_loop)
    ch = "test-state-asyncio-ch"
    pubnub.config.uuid = "test-state-asyncio-uuid"
    state = {"name": "Alex", "count": 5}

    env = yield from pubnub.set_state().channels(ch).state(state).future()

    assert env.result.state["name"] == "Alex"
    assert env.result.state["count"] == 5
Example #10
0
# get env
import os
# random generator
import secrets, string
# TUI for ask pseudo
import curses
from curses.textpad import Textbox
# to ensure that every pseudo will be the only one

# PubNub
import pubnub
from pubnub.pubnub import PubNub
from pubnub.pnconfiguration import PNConfiguration
from pubnub.enums import PNReconnectionPolicy

pubnub.set_stream_logger('pubnub', level=pubnub.logging.CRITICAL)


def initPubNub(stdscr):
    """
    Ask for a pseudo if not in the path and init the pubnub.PubNub object.

    Parameters
    ----------
        stdscr: :class:curses._CursesWindow
            the screen initialised in main.py

    Returns
    -------
    :class:pubnub.PubNub
        with configuration
Example #11
0
# PubNub HereNow usage example
import logging
import os
import sys

d = os.path.dirname
PUBNUB_ROOT = d(d(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(PUBNUB_ROOT)

import pubnub
from examples import pnconf
from pubnub.pubnub import PubNub, NonSubscribeListener


pubnub.set_stream_logger("pubnub", logging.DEBUG, stream=sys.stdout)

pubnub = PubNub(pnconf)


listener = NonSubscribeListener()

pubnub.publish().channel("blah").message("hey").async(listener.callback)

result = listener.await_result_and_reset(5)
# FIX: returns None
print(result)

pubnub.stop()