Example #1
0
def test_subscribe_publish_unsubscribe(event_loop):
    pubnub_sub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop)
    pubnub_pub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop)
    pubnub_sub.config.uuid = 'test-subscribe-asyncio-uuid-sub'
    pubnub_pub.config.uuid = 'test-subscribe-asyncio-uuid-pub'

    callback = SubscribeListener()
    channel = "test-subscribe-asyncio-ch"
    message = "hey"
    pubnub_sub.add_listener(callback)
    pubnub_sub.subscribe().channels(channel).execute()

    yield from callback.wait_for_connect()

    publish_future = asyncio.ensure_future(pubnub_pub.publish().channel(channel).message(message).future())
    subscribe_message_future = asyncio.ensure_future(callback.wait_for_message_on(channel))

    yield from asyncio.wait([
        publish_future,
        subscribe_message_future
    ])

    publish_envelope = publish_future.result()
    subscribe_envelope = subscribe_message_future.result()

    assert isinstance(subscribe_envelope, PNMessageResult)
    assert subscribe_envelope.channel == channel
    assert subscribe_envelope.subscription is None
    assert subscribe_envelope.message == message
    assert subscribe_envelope.timetoken > 0

    assert isinstance(publish_envelope, AsyncioEnvelope)
    assert publish_envelope.result.timetoken > 0
    assert publish_envelope.status.original_response[0] == 1

    pubnub_sub.unsubscribe().channels(channel).execute()
    yield from callback.wait_for_disconnect()

    pubnub_pub.stop()
    pubnub_sub.stop()
Example #2
0
    def __init__(self, subkey, pubkey, id):
        """Class constructor
        :param subkey: PubNub subscription key
        :param pubkey: PubNub publish key
        :param id: device id (UUID)
        """
        class MySubscribeListener(SubscribeListener):
            def __init__(self):
                self._logger = logging.getLogger('sprinkler')
                super().__init__()

            def status(self, pubnub, status):
                if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory:
                    # This event happens when radio / connectivity is lost
                    self._logger.error("Unexpected disconnection")

                elif status.category == PNStatusCategory.PNConnectedCategory:
                    # Connect event. You can do stuff like publish, and know you'll get it.
                    # Or just use the connected event to confirm you are subscribed for
                    # UI / internal notifications, etc
                    self._logger.info("Connection OK")

                elif status.category == PNStatusCategory.PNReconnectedCategory:
                    # Happens as part of our regular operation. This event happens when
                    # radio / connectivity is lost, then regained.
                    self._logger.info("Reconnection OK")
                elif status.category == PNStatusCategory.PNDecryptionErrorCategory:
                    # Handle message decryption error. Probably client configured to
                    # encrypt messages and on live data feed it received plain text.
                    self._logger.error("Decryption error")
                super().status(pubnub, status)

            def message(self, pubnub, message):
                if message.publisher != pubnub.uuid:
                    self._logger.debug(f"RECV from {message.publisher}: \
                        {json.dumps(message.message['content'])}")
                    super().message(pubnub, message.message['content'])

        self._logger = logging.getLogger('sprinkler')
        self.message_listener = MySubscribeListener()
        self.messages = self.message_listener.message_queue

        pnconfig = PNConfiguration()
        pnconfig.subscribe_key = subkey
        pnconfig.publish_key = pubkey
        pnconfig.uuid = id
        pnconfig.ssl = True
        pnconfig.reconnect_policy = PNReconnectionPolicy.LINEAR
        pnconfig.subscribe_timeout = 20
        self.pubnub = PubNubAsyncio(pnconfig)
        self.pubnub.add_listener(self.message_listener)
        self.pubnub.subscribe().channels('sprinkler').execute()
Example #3
0
def async_create_pubnub(user_uuid, subscriptions):
    """Create a pubnub subscription."""
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = AUGUST_CHANNEL
    pnconfig.uuid = f"pn-{str(user_uuid).upper()}"
    pubnub = PubNubAsyncio(pnconfig)
    pubnub.add_listener(subscriptions)
    pubnub.subscribe().channels(subscriptions.channels).execute()

    def _unsub():
        pubnub.unsubscribe().channels(subscriptions.channels).execute()

    return _unsub
Example #4
0
def test_send_and_download_file_encrypted(event_loop, file_for_upload, file_upload_test_data):
    pubnub = PubNubAsyncio(pnconf_file_copy(), custom_event_loop=event_loop)
    envelope = yield from send_file(pubnub, file_for_upload, cipher_key="test")
    download_envelope = yield from pubnub.download_file().\
        channel(CHANNEL).\
        file_id(envelope.result.file_id).\
        file_name(envelope.result.name).\
        cipher_key("test").\
        future()

    assert isinstance(download_envelope.result, PNDownloadFileResult)
    assert download_envelope.result.data == bytes(file_upload_test_data["FILE_CONTENT"], "utf-8")
    pubnub.stop()
Example #5
0
async def test_delete_file(event_loop, file_for_upload):
    pubnub = PubNubAsyncio(pnconf_file_copy(), custom_event_loop=event_loop)
    pubnub.config.uuid = "files_asyncio_uuid"

    envelope = await send_file(pubnub, file_for_upload)

    delete_envelope = await pubnub.delete_file().\
        channel(CHANNEL).\
        file_id(envelope.result.file_id).\
        file_name(envelope.result.name).future()

    assert isinstance(delete_envelope.result, PNDeleteFileResult)
    pubnub.stop()
Example #6
0
async def pubnub_bot(setenv):
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = os.environ['SUBKEY']
    pnconfig.publish_key = os.environ['PUBKEY']
    pnconfig.subscribe_timeout = 20
    pnconfig.uuid = "d301009f-f274-435d-b2bb-40735d944392"
    pnconfig.ssl = True

    pubnub_bot = PubNubAsyncio(pnconfig)

    yield pubnub_bot
    pubnub_bot.unsubscribe_all()
    await pubnub_bot.stop()
Example #7
0
def test_publish_file_message_with_encryption(event_loop, file_upload_test_data):
    pubnub = PubNubAsyncio(pnconf_file_copy(), custom_event_loop=event_loop)
    envelope = yield from PublishFileMessage(pubnub).\
        channel(CHANNEL).\
        meta({}).\
        message({"test": "test"}).\
        file_id("2222").\
        file_name("test").\
        should_store(True).\
        ttl(222).future()

    assert isinstance(envelope.result, PNPublishFileMessageResult)
    pubnub.stop()
Example #8
0
async def test_single_channel(event_loop):
    pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop)
    pubnub.config.uuid = "my_uuid"
    ch = "test-pam-asyncio-ch"

    env = await pubnub.grant().channels(ch).write(True).read(True).future()

    assert isinstance(env.result, PNAccessManagerGrantResult)
    assert env.result.channels[ch].read_enabled == 1
    assert env.result.channels[ch].write_enabled == 1
    assert env.result.channels[ch].manage_enabled == 0
    assert env.result.channels[ch].delete_enabled == 0

    await pubnub.stop()
def test_access_denied_unsubscribe_operation(event_loop):
    channel = "not-permitted-channel"
    pnconf = pnconf_pam_copy()
    pnconf.secret_key = None
    pnconf.enable_subscribe = True

    pubnub = PubNubAsyncio(pnconf, custom_event_loop=event_loop)

    callback = AccessDeniedListener()
    pubnub.add_listener(callback)

    pubnub.subscribe().channels(channel).execute()
    yield from callback.access_denied_event.wait()

    pubnub.stop()
Example #10
0
async def test_global_level(event_loop):
    pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop)
    pubnub.config.uuid = "my_uuid"

    env = await pubnub.grant().write(True).read(True).future()

    assert isinstance(env.result, PNAccessManagerGrantResult)
    assert len(env.result.channels) == 0
    assert len(env.result.groups) == 0
    assert env.result.read_enabled is True
    assert env.result.write_enabled is True
    assert env.result.manage_enabled is False
    assert env.result.delete_enabled is False

    await pubnub.stop()
Example #11
0
async def test_single_channel_group(event_loop):
    pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop)
    pubnub.config.uuid = "test-pam-asyncio-uuid"
    cg = "test-pam-asyncio-cg"

    env = await pubnub.grant().channel_groups(cg).write(True).read(True
                                                                   ).future()

    assert isinstance(env.result, PNAccessManagerGrantResult)
    assert env.result.level == 'channel-group'
    assert env.result.groups[cg].read_enabled == 1
    assert env.result.groups[cg].write_enabled == 1
    assert env.result.groups[cg].manage_enabled == 0
    assert env.result.groups[cg].delete_enabled == 0

    await pubnub.stop()
Example #12
0
async def test_single_channel_group_with_auth(event_loop):
    pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop)
    pubnub.config.uuid = "test-pam-asyncio-uuid"
    gr = "test-pam-asyncio-cg"
    auth = "test-pam-asyncio-auth"

    env = await pubnub.grant().channel_groups(gr).write(True).read(
        True).auth_keys(auth).future()

    assert isinstance(env.result, PNAccessManagerGrantResult)
    assert env.result.level == 'channel-group+auth'
    assert env.result.groups[gr].auth_keys[auth].read_enabled == 1
    assert env.result.groups[gr].auth_keys[auth].write_enabled == 1
    assert env.result.groups[gr].auth_keys[auth].manage_enabled == 0
    assert env.result.groups[gr].auth_keys[auth].delete_enabled == 0

    await pubnub.stop()
def test_get_spaces(event_loop):
    config = pnconf_obj_copy()
    pn = PubNubAsyncio(config, custom_event_loop=event_loop)
    envelope = yield from pn.get_spaces().include('custom').future()

    assert (isinstance(envelope, AsyncioEnvelope))
    assert not envelope.status.is_error()
    assert isinstance(envelope.result, PNGetSpacesResult)
    assert isinstance(envelope.status, PNStatus)
    data = envelope.result.data
    assert len(data) == 100
    assert set(
        ['name', 'id', 'description', 'custom', 'created', 'updated',
         'eTag']) == set(data[0])
    assert set(
        ['name', 'id', 'description', 'custom', 'created', 'updated',
         'eTag']) == set(data[1])
Example #14
0
async def test_here_now_super_call(event_loop):
    pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop)
    pubnub.config.uuid = 'test-here-now-asyncio-uuid1'

    env = await pubnub.here_now().future()
    assert isinstance(env.result, PNHereNowResult)

    env = await pubnub.here_now().channel_groups("gr").include_uuids(True).include_state(True).future()
    assert isinstance(env.result, PNHereNowResult)

    env = await pubnub.here_now().channels('ch.bar*').channel_groups("gr.k").future()
    assert isinstance(env.result, PNHereNowResult)

    env = await pubnub.here_now().channels(['ch.bar*', 'ch2']).channel_groups("gr.k").future()
    assert isinstance(env.result, PNHereNowResult)

    pubnub.stop()
Example #15
0
    async def __aenter__(self):
        message_decrypter = BeekeeperBotMessageDecrypter(
            base64.b64decode(self._pubnub_channel_key))
        message_listener = BeekeeperBotMessageListener(
            bot=self, decrypter=message_decrypter)

        pubnub_config = PNConfiguration()
        pubnub_config.subscribe_key = self._pubnub_key
        pubnub_config.reconnect_policy = PNReconnectionPolicy.LINEAR
        pubnub_config.connect_timeout = 30

        self._pubnub = PubNubAsyncio(config=pubnub_config)
        self._pubnub.add_listener(message_listener)
        self._pubnub.subscribe().channels([self._pubnub_channel_name
                                           ]).execute()

        return self
async def test_unsubscribe_all(event_loop, sleeper=asyncio.sleep):
    pubnub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop)

    pubnub.config.uuid = "test-subscribe-asyncio-messenger"

    ch = "test-subscribe-asyncio-unsubscribe-all-ch"
    ch1 = "test-subscribe-asyncio-unsubscribe-all-ch1"
    ch2 = "test-subscribe-asyncio-unsubscribe-all-ch2"
    ch3 = "test-subscribe-asyncio-unsubscribe-all-ch3"
    gr1 = "test-subscribe-asyncio-unsubscribe-all-gr1"
    gr2 = "test-subscribe-asyncio-unsubscribe-all-gr2"

    envelope = await pubnub.add_channel_to_channel_group().channel_group(
        gr1).channels(ch).future()
    assert envelope.status.original_response['status'] == 200
    envelope = await pubnub.add_channel_to_channel_group().channel_group(
        gr2).channels(ch).future()
    assert envelope.status.original_response['status'] == 200

    await sleeper(1)

    callback_messages = VCR599Listener(1)
    pubnub.add_listener(callback_messages)

    pubnub.subscribe().channels([ch1, ch2,
                                 ch3]).channel_groups([gr1, gr2]).execute()
    await callback_messages.wait_for_connect()

    assert len(pubnub.get_subscribed_channels()) == 3
    assert len(pubnub.get_subscribed_channel_groups()) == 2

    pubnub.unsubscribe_all()

    await callback_messages.wait_for_disconnect()

    assert len(pubnub.get_subscribed_channels()) == 0
    assert len(pubnub.get_subscribed_channel_groups()) == 0

    envelope = await pubnub.remove_channel_from_channel_group().channel_group(
        gr1).channels(ch).future()
    assert envelope.status.original_response['status'] == 200
    envelope = await pubnub.remove_channel_from_channel_group().channel_group(
        gr2).channels(ch).future()
    assert envelope.status.original_response['status'] == 200

    await pubnub.stop()
async def test_send_and_download_file_encrypted(event_loop, file_for_upload,
                                                file_upload_test_data):
    pubnub = PubNubAsyncio(pnconf_file_copy(), custom_event_loop=event_loop)

    with patch("pubnub.crypto.PubNubCryptodome.get_initialization_vector",
               return_value="knightsofni12345"):
        envelope = await send_file(pubnub, file_for_upload, cipher_key="test")
        download_envelope = await pubnub.download_file().\
            channel(CHANNEL).\
            file_id(envelope.result.file_id).\
            file_name(envelope.result.name).\
            cipher_key("test").\
            future()

        assert isinstance(download_envelope.result, PNDownloadFileResult)
        assert download_envelope.result.data == bytes(
            file_upload_test_data["FILE_CONTENT"], "utf-8")
        await pubnub.stop()
def test_get_space(event_loop):
    config = pnconf_obj_copy()
    pn = PubNubAsyncio(config, custom_event_loop=event_loop)
    envelope = yield from pn.get_space().space_id('in_space').include(
        'custom').future()

    assert (isinstance(envelope, AsyncioEnvelope))
    assert not envelope.status.is_error()
    assert isinstance(envelope.result, PNGetSpaceResult)
    assert isinstance(envelope.status, PNStatus)
    data = envelope.result.data
    assert set(
        ['name', 'id', 'description', 'created', 'updated', 'eTag',
         'custom']) == set(data)
    assert data['id'] == 'in_space'
    assert data['name'] == 'some_name'
    assert data['custom'] == {'a': 3}
    assert data['description'] is None
def test_create_user(event_loop):
    config = pnconf_obj_copy()
    pn = PubNubAsyncio(config, custom_event_loop=event_loop)
    data = {'id': 'mg', 'name': 'MAGNUM', 'custom': {'XXX': 'YYYY'}}
    envelope = yield from pn.create_user().data(data).include(
        'custom').future()

    assert (isinstance(envelope, AsyncioEnvelope))
    assert not envelope.status.is_error()
    assert isinstance(envelope.result, PNCreateUserResult)
    assert isinstance(envelope.status, PNStatus)
    data = envelope.result.data
    assert data['id'] == 'mg'
    assert data['name'] == 'MAGNUM'
    assert data['externalId'] is None
    assert data['profileUrl'] is None
    assert data['email'] is None
    assert data['custom'] == {'XXX': 'YYYY'}
async def test_cg_subscribe_publish_unsubscribe(event_loop,
                                                sleeper=asyncio.sleep):
    ch = "test-subscribe-asyncio-channel"
    gr = "test-subscribe-asyncio-group"
    message = "hey"

    pubnub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop)

    envelope = await pubnub.add_channel_to_channel_group().channel_group(
        gr).channels(ch).future()
    assert envelope.status.original_response['status'] == 200

    await sleeper(1)

    callback_messages = VCR599Listener(1)
    pubnub.add_listener(callback_messages)
    pubnub.subscribe().channel_groups(gr).execute()
    await callback_messages.wait_for_connect()

    subscribe_future = asyncio.ensure_future(
        callback_messages.wait_for_message_on(ch))
    publish_future = asyncio.ensure_future(
        pubnub.publish().channel(ch).message(message).future())
    await asyncio.wait([subscribe_future, publish_future])

    sub_envelope = subscribe_future.result()
    pub_envelope = publish_future.result()

    assert pub_envelope.status.original_response[0] == 1
    assert pub_envelope.status.original_response[1] == 'Sent'

    assert sub_envelope.channel == ch
    assert sub_envelope.subscription == gr
    assert sub_envelope.message == message

    pubnub.unsubscribe().channel_groups(gr).execute()
    await callback_messages.wait_for_disconnect()

    envelope = await pubnub.remove_channel_from_channel_group().channel_group(
        gr).channels(ch).future()
    assert envelope.status.original_response['status'] == 200

    await pubnub.stop()
Example #21
0
def test_state_super_admin_call(event_loop):
    pnconf = pnconf_pam_copy()
    pubnub = PubNubAsyncio(pnconf, custom_event_loop=event_loop)
    ch1 = 'test-state-asyncio-ch1'
    ch2 = 'test-state-asyncio-ch2'
    pubnub.config.uuid = 'test-state-asyncio-uuid'
    state = {"name": "Alex", "count": 5}

    env = yield from pubnub.set_state() \
        .channels([ch1, ch2]) \
        .state(state) \
        .future()
    assert isinstance(env.result, PNSetStateResult)

    env = yield from pubnub.get_state() \
        .channels([ch1, ch2]) \
        .future()
    assert isinstance(env.result, PNGetStateResult)

    pubnub.stop()
def test_create_space(event_loop):
    config = pnconf_obj_copy()
    pn = PubNubAsyncio(config, custom_event_loop=event_loop)
    envelope = yield from pn.create_space().data({
        'id': 'in_space',
        'name': 'some_name',
        'custom': {
            'a': 3
        }
    }).include('custom').future()

    assert (isinstance(envelope, AsyncioEnvelope))
    assert not envelope.status.is_error()
    assert isinstance(envelope.result, PNCreateSpaceResult)
    assert isinstance(envelope.status, PNStatus)
    data = envelope.result.data
    assert data['id'] == 'in_space'
    assert data['name'] == 'some_name'
    assert data['custom'] == {'a': 3}
    assert data['description'] is None
Example #23
0
def test_single_channel_with_auth(event_loop):
    pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop)
    pubnub.config.uuid = "test-pam-asyncio-uuid"
    ch = "test-pam-asyncio-ch"
    auth = "test-pam-asyncio-auth"

    env = (yield from pubnub.grant()
           .channels(ch)
           .write(True)
           .read(True)
           .auth_keys(auth)
           .future())

    assert isinstance(env.result, PNAccessManagerGrantResult)
    assert env.result.channels[ch].auth_keys[auth].read_enabled == 1
    assert env.result.channels[ch].auth_keys[auth].write_enabled == 1
    assert env.result.channels[ch].auth_keys[auth].manage_enabled == 0
    assert env.result.channels[ch].auth_keys[auth].delete_enabled == 0

    pubnub.stop()
Example #24
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 #25
0
async def test_multiple_channels(event_loop):
    pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop)
    pubnub.config.uuid = "test-pam-asyncio-uuid"
    ch1 = "test-pam-asyncio-ch1"
    ch2 = "test-pam-asyncio-ch2"

    env = await pubnub.grant().channels([ch1,
                                         ch2]).write(True).read(True).future()

    assert isinstance(env.result, PNAccessManagerGrantResult)
    assert env.result.channels[ch1].read_enabled is True
    assert env.result.channels[ch2].read_enabled is True
    assert env.result.channels[ch1].write_enabled is True
    assert env.result.channels[ch2].write_enabled is True
    assert env.result.channels[ch1].manage_enabled is False
    assert env.result.channels[ch2].manage_enabled is False
    assert env.result.channels[ch1].delete_enabled is False
    assert env.result.channels[ch2].delete_enabled is False

    await pubnub.stop()
Example #26
0
async def test_multiple_channels(event_loop, sleeper=asyncio.sleep):
    pubnub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop)
    pubnub.config.uuid = 'test-here-now-asyncio-uuid1'

    ch1 = "test-here-now-asyncio-ch1"
    ch2 = "test-here-now-asyncio-ch2"

    callback = VCR599Listener(1)
    pubnub.add_listener(callback)
    pubnub.subscribe().channels([ch1, ch2]).execute()

    await callback.wait_for_connect()

    await sleeper(5)

    env = await pubnub.here_now() \
        .channels([ch1, ch2]) \
        .future()

    assert env.result.total_channels == 2
    assert env.result.total_occupancy >= 1

    channels = env.result.channels

    assert len(channels) == 2
    assert channels[0].occupancy == 1
    assert channels[0].occupants[0].uuid == pubnub.uuid
    assert channels[1].occupancy == 1
    assert channels[1].occupants[0].uuid == pubnub.uuid

    result = await pubnub.here_now() \
        .channels([ch1, ch2]) \
        .include_state(True) \
        .result()

    assert result.total_channels == 2

    pubnub.unsubscribe().channels([ch1, ch2]).execute()
    await callback.wait_for_disconnect()

    pubnub.stop()
def test_blah():
    pnconf = pnconf_sub_copy()
    assert isinstance(pnconf, PNConfiguration)
    pnconf.reconnect_policy = PNReconnectionPolicy.EXPONENTIAL
    pubnub = PubNubAsyncio(pnconf)
    time_until_open_again = 8

    @asyncio.coroutine
    def close_soon():
        yield from asyncio.sleep(2)
        pubnub._connector.close()
        print(">>> connection is broken")

    @asyncio.coroutine
    def open_again():
        yield from asyncio.sleep(time_until_open_again)
        pubnub.set_connector(aiohttp.TCPConnector(conn_timeout=pubnub.config.connect_timeout, verify_ssl=True))
        print(">>> connection is open again")

    @asyncio.coroutine
    def countdown():
        asyncio.sleep(2)
        opened = False
        count = time_until_open_again

        while not opened:
            print(">>> %ds to open again" % count)
            count -= 1
            if count <= 0:
                break
            yield from asyncio.sleep(1)

    my_listener = MySubscribeCallback()
    pubnub.add_listener(my_listener)
    pubnub.subscribe().channels('my_channel').execute()

    asyncio.ensure_future(close_soon())
    asyncio.ensure_future(open_again())
    asyncio.ensure_future(countdown())

    yield from asyncio.sleep(1000)
Example #28
0
    async def message_pump(self):
        pnconfig = PNConfiguration()
        pnconfig.subscribe_key = config['cardsubkey']
        # Why aren't these the default settings?
        pnconfig.ssl = True
        pnconfig.reconnect_policy = PNReconnectionPolicy.EXPONENTIAL

        pubnub = PubNubAsyncio(pnconfig)

        listener = SubscribeListener()
        pubnub.add_listener(listener)

        pubnub.subscribe().channels(config['cardviewerchannel']).execute()
        await listener.wait_for_connect()
        log.info("Connected to PubNub")

        message_future = asyncio.ensure_future(
            listener.wait_for_message_on(config['cardviewerchannel']))

        while True:
            await asyncio.wait([self.stop_future, message_future],
                               return_when=asyncio.FIRST_COMPLETED)
            if message_future.done():
                message = message_future.result().message
                log.info("Message from PubNub: %r", message)

                card_id = self._extract(message)
                if card_id is not None:
                    await self._card(card_id)

                message_future = asyncio.ensure_future(
                    listener.wait_for_message_on(config['cardviewerchannel']))
            if self.stop_future.done():
                break
        if not message_future.done():
            message_future.cancel()

        pubnub.unsubscribe().channels(config['cardviewerchannel']).execute()
        await listener.wait_for_disconnect()
        pubnub.stop()
        log.info("Disconnected from PubNub")
Example #29
0
async def test_add_remove_single_channel(event_loop, sleeper=asyncio.sleep):
    pubnub = PubNubAsyncio(pnconf_copy(), custom_event_loop=event_loop)
    pubnub.config.uuid = 'test-channel-group-asyncio-uuid1'

    ch = "test-channel-groups-asyncio-ch"
    gr = "test-channel-groups-asyncio-cg"

    await pubnub.publish().channel(ch).message("hey").future()
    # add
    env = await pubnub.add_channel_to_channel_group() \
        .channels(ch).channel_group(gr).future()

    assert isinstance(env.result, PNChannelGroupsAddChannelResult)

    await sleeper(1)

    # list
    env = await pubnub.list_channels_in_channel_group().channel_group(
        gr).future()
    assert isinstance(env.result, PNChannelGroupsListResult)
    assert len(env.result.channels) == 1
    assert env.result.channels[0] == ch

    # remove
    env = await pubnub.remove_channel_from_channel_group() \
        .channels(ch).channel_group(gr).future()

    assert isinstance(env.result, PNChannelGroupsRemoveChannelResult)

    await sleeper(1)

    # change uuid to let vcr to distinguish list requests
    pubnub.config.uuid = 'test-channel-group-asyncio-uuid2'

    # list
    env = await pubnub.list_channels_in_channel_group().channel_group(
        gr).future()
    assert isinstance(env.result, PNChannelGroupsListResult)
    assert len(env.result.channels) == 0

    pubnub.stop()
Example #30
0
async def test_multiple_channel_groups_with_auth(event_loop):
    pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop)
    pubnub.config.uuid = "my_uuid"
    gr1 = "test-pam-asyncio-cg1"
    gr2 = "test-pam-asyncio-cg2"
    auth = "test-pam-asyncio-auth"

    env = await pubnub.grant().channel_groups(
        [gr1, gr2]).write(True).read(True).auth_keys(auth).future()

    assert isinstance(env.result, PNAccessManagerGrantResult)
    assert env.result.groups[gr1].auth_keys[auth].read_enabled is True
    assert env.result.groups[gr2].auth_keys[auth].read_enabled is True
    assert env.result.groups[gr1].auth_keys[auth].write_enabled is True
    assert env.result.groups[gr2].auth_keys[auth].write_enabled is True
    assert env.result.groups[gr1].auth_keys[auth].manage_enabled is False
    assert env.result.groups[gr2].auth_keys[auth].manage_enabled is False
    assert env.result.groups[gr1].auth_keys[auth].delete_enabled is False
    assert env.result.groups[gr2].auth_keys[auth].delete_enabled is False

    await pubnub.stop()