Пример #1
0
    async def test_recover_on_temporary_network_outage(self):
        # create client
        async with Client(self.COMETD_URL,
                          self.CONNECTION_TYPE,
                          connection_timeout=1) as client:
            # subscribe to the room's channel
            await client.subscribe(self.CHAT_ROOM_CHANNEL)

            # pause the service
            self.container.pause()
            # wait for the server's connect request timeout to elapse to be
            # able to detect the problem
            await asyncio.sleep(client._transport.request_timeout)
            # give a few seconds for the client to detect the lost connection
            await asyncio.sleep(3)

            # start the service
            self.container.ensure_reachable()
            # give a few seconds for the client to recover the connection
            await asyncio.sleep(3)

            # send a chat message
            chat_message = {"user": self.USER_NAME1, "chat": "test_message"}
            await client.publish(self.CHAT_ROOM_CHANNEL, chat_message)
            # verify chat message
            message = await client.receive()
            self.assertEqual(message, {
                "data": chat_message,
                "channel": self.CHAT_ROOM_CHANNEL
            })
Пример #2
0
    async def test_revover_on_server_restart(self):
        # create client
        async with Client(self.COMETD_URL,
                          self.CONNECTION_TYPE,
                          connection_timeout=3 * 60) as client:
            # subscribe to the room's channel
            await client.subscribe(self.CHAT_ROOM_CHANNEL)

            # stop the service
            self.container.stop()
            # give a few seconds for the client to detect the lost connection
            await asyncio.sleep(3)

            # start the service
            self.container.ensure_reachable()
            # give a few seconds for the client to recover the connection
            await asyncio.sleep(3)

            # send a chat message
            chat_message = {"user": self.USER_NAME1, "chat": "test_message"}
            await client.publish(self.CHAT_ROOM_CHANNEL, chat_message)
            # verify chat message
            message = await client.receive()
            self.assertEqual(message, {
                "data": chat_message,
                "channel": self.CHAT_ROOM_CHANNEL
            })
    async def __subscribe_and_run(self):
        channels = self.__get_channels()
        channels_dict = dict(zip(channels, self.queries))

        # connect to the server
        async with Client(self.server + "/cometd") as client:
            for channel in channels:
                # subscribe to channel to receive events
                await client.subscribe(channel)
            async for message in client:
                query = channels_dict[message['channel']]
                data = message["data"]
                for listener in query.listeners:
                    listener.on_event(data)
Пример #4
0
    async def test_timeout_on_server_termination(self):
        # create client
        async with Client(self.COMETD_URL,
                          self.CONNECTION_TYPE,
                          connection_timeout=1) as client:
            # subscribe to the room's channel
            await client.subscribe(self.CHAT_ROOM_CHANNEL)

            # stop the service
            self.container.stop()
            # give a few seconds for the client to detect the lost connection
            await asyncio.sleep(3)

            with self.assertRaises(TransportTimeoutError):
                await client.receive()
Пример #5
0
 async def go():
     self.gameid = pin
     data = await resolve(self.gameid, self)
     self.settings.update(data["data"])
     token = data["token"]
     client = Client(f"wss://kahoot.it/cometd/{self.gameid}/{token}")
     self.socket = client
     await client.open()
     await client.subscribe("/service/controller")
     await client.subscribe("/service/status")
     await client.subscribe("/service/player")
     await self._send(self.classes["LiveJoinPacket"](self, name))
     async for message in client:
         # Handle messages
         self._message(message)
     await client.close()
Пример #6
0
    async def test_timeout_network_outage(self):
        # create client
        async with Client(self.COMETD_URL,
                          self.CONNECTION_TYPE,
                          connection_timeout=1) as client:
            # subscribe to the room's channel
            await client.subscribe(self.CHAT_ROOM_CHANNEL)

            # pause the service
            self.container.pause()
            # wait for the server's connect request timeout to elapse to be
            # able to detect the problem
            await asyncio.sleep(client._transport.request_timeout)
            # give a few seconds for the client to detect the lost connection
            await asyncio.sleep(3)

            with self.assertRaises(TransportTimeoutError):
                await client.receive()
Пример #7
0
    async def test_single_client_chat(self):
        # create client
        async with Client(self.COMETD_URL, self.CONNECTION_TYPE) as client:
            # subscribe to channels
            await client.subscribe(self.CHAT_ROOM_CHANNEL)
            await client.subscribe(self.MEMBERS_CHANGED_CHANNEL)

            # send initial message
            join_message = {
                "user": self.USER_NAME1,
                "membership": "join",
                "chat": self.USER_NAME1 + " has joined"
            }
            await client.publish(self.CHAT_ROOM_CHANNEL, join_message)
            # add the user to the room's members
            await client.publish(self.MEMBERS_CHANNEL, {
                "user": self.USER_NAME1,
                "room": self.CHAT_ROOM_CHANNEL
            })

            # verify the reception of the initial and members messages
            message = await client.receive()
            self.assertEqual(message, {
                "data": join_message,
                "channel": self.CHAT_ROOM_CHANNEL
            })
            message = await client.receive()
            self.assertEqual(message, {
                "data": [self.USER_NAME1],
                "channel": self.MEMBERS_CHANGED_CHANNEL
            })

            # send a chat message
            chat_message = {"user": self.USER_NAME1, "chat": "test_message"}
            await client.publish(self.CHAT_ROOM_CHANNEL, chat_message)
            # verify chat message
            message = await client.receive()
            self.assertEqual(message, {
                "data": chat_message,
                "channel": self.CHAT_ROOM_CHANNEL
            })
Пример #8
0
async def read_results(url, channels, output_queue):
    setproctitle("live-client: cometd client for channels {}".format(channels))

    with ensure_timeout(3.05):
        with start_action(action_type="query.read_results",
                          url=url,
                          channels=channels):
            # connect to the server
            async with Client(url) as client:
                for channel in channels:
                    logging.debug(f"Subscribing to '{channel}'")
                    await client.subscribe(channel)

                # listen for incoming messages
                async for message in client:
                    logging.debug(f"New message'{message}'")
                    output_queue.put(message)

                    # Exit after the query has stopped
                    event_data = message.get("data", {})
                    event_type = event_data.get("type")
                    if event_type == EVENT_TYPE_DESTROY:
                        return
Пример #9
0
 async def run(self):
     # connect to the server
     while (True):
         logging.info('Starting WS')
         async with Client("https://www.missionchief.co.uk/faye",
                           extensions=[MyExtension()]) as client:
             await client.subscribe("/allen_GB")
             # await client.subscribe("/private-alliance/019398d6-1a5b-41d8-a590-d4e373c9eff5/en_GB")
             await client.subscribe("/private-user2091en_GB")
             logging.info("Subscribed to WS")
             self.queue.put({
                 'type': 'ws_start',
             })
             # listen for incoming messages
             async for message in client:
                 if ('data' not in message):
                     logging.warning('Issue found {}'.format(message))
                 else:
                     matches = re.finditer(
                         r"([a-zA-Z]+)\(\s?([^;]+}?\s?)\);",
                         message['data'], re.MULTILINE)
                     # if (matches.group(1))
                     for match in matches:
                         try:
                             data = json.loads(match.group(2))
                         except json.decoder.JSONDecodeError:
                             logging.info('JSON error reported {}'.format(
                                 match.group(2)))
                             data = match.group(2)
                         if match.group(1) == 'missionMarkerAdd':
                             self.add_mission(data)
                         elif match.group(1) == 'patientMarkerAdd':
                             self.queue.put({
                                 'type': 'patient_add',
                                 'data': data
                             })
                         elif match.group(1) == 'patientDelete':
                             self.queue.put({
                                 'type': 'patient_delete',
                                 'data': data
                             })
                             # patientMarkerAddCombined
                         elif match.group(1) == 'patientMarkerAddCombined':
                             self.queue.put({
                                 'type': 'patientcombined_add',
                                 'data': data
                             })
                         elif match.group(1) == 'prisonerMarkerAdd':
                             self.queue.put({
                                 'type': 'prisonermarker_add',
                                 'data': data
                             })
                         elif match.group(1) == 'radioMessage':
                             self.radio_message(data)
                         # elif match.group(1) == 'missionDelete':
                         #     self.del_mission(data)
                         elif match.group(1) == 'deleteMission':
                             self.del_mission(data)
                         elif match.group(1) == 'vehicleMarkerAdd':
                             # matches = re.finditer(r"([a-zA-Z]+)((\s?([^;]+}\s?)));", data, re.MULTILINE)
                             # for match in matches:
                             #     try:
                             #         specific = json.loads(match.group(2))
                             #         self.add_unit(specific)
                             #     except json.decoder.JSONDecodeError:
                             #         continue
                             pass
                         elif match.group(1) == 'vehicleDrive':
                             pass
                         else:
                             logging.info('Not handling {} {}'.format(
                                 match.group(1), match.group(2)))
Пример #10
0
async def chat_client(url: str, nickname: str,
                      connection_type: ConnectionType) -> None:
    """Runs the chat client until it's canceled

    :param url: CometD server URL
    :param nickname: The user's nickname
    :param connection_type: Connection type
    """
    try:
        room_name = "demo"
        room_channel = "/chat/" + room_name
        members_changed_channel = "/members/" + room_name
        members_channel = "/service/members"

        # start the client with the given connection type
        async with Client(url, connection_type) as client:
            print(f"Connected to '{url}' using connection "
                  f"type '{connection_type.value}'\n")

            # subscribe to the chat room's channel to receive messages
            await client.subscribe(room_channel)

            # subscribe to the members channel to get notifications when the
            # list of the room's members changes
            await client.subscribe(members_changed_channel)

            # publish to the room's channel that the user has joined
            await client.publish(room_channel, {
                "user": nickname,
                "membership": "join",
                "chat": nickname + " has joined"
            })

            # add the user to the room's members
            await client.publish(members_channel, {
                "user": nickname,
                "room": room_channel
            })

            # start the message publisher task
            input_task = asyncio.ensure_future(
                input_publisher(client, nickname, room_channel))

            last_user = None
            try:
                # listen for incoming messages
                async for message in client:
                    # if a chat message is received
                    if message["channel"] == room_channel:
                        data = message["data"]
                        if data["user"] == last_user:
                            user = "******"
                        else:
                            last_user = data["user"]
                            user = data["user"] + ":"
                        # print the incoming message
                        print(f"{user} {data['chat']}")

                    # if the room's members change
                    elif message["channel"] == members_changed_channel:
                        print("MEMBERS:", ", ".join(message["data"]))
                        last_user = None

            finally:
                input_task.cancel()

    except AiocometdException as error:
        print("Encountered an error: " + str(error))
    except asyncio.CancelledError:
        pass
    finally:
        print("\nExiting...")
Пример #11
0
    async def test_multi_client_chat(self):
        # create two clients
        async with Client(self.COMETD_URL, self.CONNECTION_TYPE) as client1, \
                Client(self.COMETD_URL, self.CONNECTION_TYPE) as client2:
            # subscribe to channels with client1
            await client1.subscribe(self.CHAT_ROOM_CHANNEL)
            await client1.subscribe(self.MEMBERS_CHANGED_CHANNEL)

            # send initial message with client1
            join_message1 = {
                "user": self.USER_NAME1,
                "membership": "join",
                "chat": self.USER_NAME1 + " has joined"
            }
            await client1.publish(self.CHAT_ROOM_CHANNEL, join_message1)
            # add the user1 to the room's members
            await client1.publish(self.MEMBERS_CHANNEL, {
                "user": self.USER_NAME1,
                "room": self.CHAT_ROOM_CHANNEL
            })

            # verify the reception of the initial and members messages
            # for client1
            message = await client1.receive()
            self.assertEqual(message, {
                "data": join_message1,
                "channel": self.CHAT_ROOM_CHANNEL
            })
            message = await client1.receive()
            self.assertEqual(message, {
                "data": [self.USER_NAME1],
                "channel": self.MEMBERS_CHANGED_CHANNEL
            })

            # subscribe to channels with client2
            await client2.subscribe(self.CHAT_ROOM_CHANNEL)
            await client2.subscribe(self.MEMBERS_CHANGED_CHANNEL)

            # send initial message with client2
            join_message2 = {
                "user": self.USER_NAME2,
                "membership": "join",
                "chat": self.USER_NAME2 + " has joined"
            }
            await client2.publish(self.CHAT_ROOM_CHANNEL, join_message2)
            # add the user2 to the room's members
            await client2.publish(self.MEMBERS_CHANNEL, {
                "user": self.USER_NAME2,
                "room": self.CHAT_ROOM_CHANNEL
            })

            # verify the reception of the initial and members messages of
            # client2 for client1
            message = await client1.receive()
            self.assertEqual(message, {
                "data": join_message2,
                "channel": self.CHAT_ROOM_CHANNEL
            })
            message = await client1.receive()
            self.assertEqual(
                message, {
                    "data": [self.USER_NAME1, self.USER_NAME2],
                    "channel": self.MEMBERS_CHANGED_CHANNEL
                })

            # verify the reception of the initial and members messages
            # for client2
            message = await client2.receive()
            self.assertEqual(message, {
                "data": join_message2,
                "channel": self.CHAT_ROOM_CHANNEL
            })
            message = await client2.receive()
            self.assertEqual(
                message, {
                    "data": [self.USER_NAME1, self.USER_NAME2],
                    "channel": self.MEMBERS_CHANGED_CHANNEL
                })