Ejemplo n.º 1
0
async def unpack(wallet_handle, message_bytes):
    try:
        unpacked = json.loads(await
                              crypto.unpack_message(wallet_handle,
                                                    message_bytes))

        from_key = None
        from_did = None
        if 'sender_verkey' in unpacked:
            from_key = unpacked['sender_verkey']
            from_did = await did_for_key(wallet_handle,
                                         unpacked['sender_verkey'])

        to_key = unpacked['recipient_verkey']
        to_did = await did_for_key(wallet_handle, unpacked['recipient_verkey'])

        msg = Message.deserialize(unpacked['message'])

        msg.context = {
            'from_did': from_did,
            'to_did': to_did,
            'from_key': from_key,
            'to_key': to_key
        }
        return msg
    except error.IndyError as indy_error:
        if indy_error.error_code is error.ErrorCode.CommonInvalidStructure:
            msg = Message.deserialize(message_bytes)
            msg.context = None
            return msg
        raise indy_error
Ejemplo n.º 2
0
async def test_http_return_route_no_endpoint(connected_client_server_agents):
    (alice, alice_did, alice_vk, bob, bob_did,
     bob_vk) = connected_client_server_agents

    alice.ponged = asyncio.Event()

    @bob.route('ping')
    async def respond(agent, msg):
        print('got ping, sending pong should queue message')
        pong = Message({'@type': 'pong'})
        await agent.conductor.send(pong,
                                   msg.context['from_key'],
                                   to_did=msg.context['from_did'],
                                   from_key=msg.context['to_key'])
        print('sent pong to queue, probably')
        print('queue up a noop')
        await agent.conductor.send(Message({'@type': 'noop'}),
                                   msg.context['from_key'],
                                   to_did=msg.context['from_did'],
                                   from_key=msg.context['to_key'])
        assert agent.conductor.queues[msg.context['from_key']].qsize() == 2

    @alice.route('noop')
    @bob.route('noop')
    async def noop(agent, msg):
        print('noop')
        pass

    @alice.route('pong')
    async def got_pong(agent, msg):
        print('got pong')
        agent.ponged.set()

    gathered_agent_tasks = asyncio.gather(alice.start(), bob.start())

    # No return route, can't respond directly
    ping = Message({'@type': 'ping'})
    await alice.conductor.send(ping, bob_vk, to_did=bob_did, from_key=alice_vk)

    print('sending noop to pump bob\'s queue')
    noop = Message({'@type': 'noop', '~transport': {'return_route': 'all'}})
    await alice.conductor.send(noop, bob_vk, to_did=bob_did, from_key=alice_vk)

    await asyncio.wait_for(alice.ponged.wait(), 5)

    await alice.shutdown()
    await bob.shutdown()
    gathered_agent_tasks.cancel()
    with suppress(asyncio.CancelledError):
        await gathered_agent_tasks

    assert alice.ponged.is_set()
Ejemplo n.º 3
0
    def load_level(self, level: str):
        player : Entity = Player(self.message_bus, Vector2(5, 5))
        
        self.message_bus.post_message(Message("ADD_ENTITY", player))
        self.message_bus.post_message(Message("ADD_CAMERA", player.get_component(MainCamera)))

        level_name = level + ".json"
        to_load_level = Path.cwd() / "levels" / "level_information" / level_name
        
        try:
            level_contents_text = open(to_load_level).read()
        except:
            log.error(f'Could not load level: {to_load_level}')
Ejemplo n.º 4
0
async def test_module_routing_many():
    """ Test that routing to a module works. """
    agent = Agent()
    agent.called_module = None
    routed_event = asyncio.Event()

    @module
    class TestModule1():
        DOC_URI = ''
        PROTOCOL = 'test_protocol'
        VERSION = '1.0'

        async def testing_type(self, agent, msg, *args, **kwargs):
            agent.called_module = 1
            kwargs['event'].set()

    @module
    class TestModule2():
        DOC_URI = ''
        PROTOCOL = 'test_protocol'
        VERSION = '2.0'

        async def testing_type(self, agent, msg, *args, **kwargs):
            agent.called_module = 2
            kwargs['event'].set()

    agent.route_module(TestModule1())
    agent.route_module(TestModule2())

    test_msg = Message({
        '@type': 'test_protocol/1.0/testing_type',
        'test': 'test'
    })
    await agent.handle(test_msg, event=routed_event)
    await routed_event.wait()

    assert routed_event.is_set()
    assert agent.called_module == 1

    routed_event.clear()

    test_msg = Message({
        '@type': 'test_protocol/2.0/testing_type',
        'test': 'test'
    })
    await agent.handle(test_msg, event=routed_event)
    await routed_event.wait()

    assert routed_event.is_set()
    assert agent.called_module == 2
Ejemplo n.º 5
0
 async def respond(agent, msg):
     print('got ping, sending pong should queue message')
     pong = Message({'@type': 'pong'})
     await agent.conductor.send(pong,
                                msg.context['from_key'],
                                to_did=msg.context['from_did'],
                                from_key=msg.context['to_key'])
     print('sent pong to queue, probably')
     print('queue up a noop')
     await agent.conductor.send(Message({'@type': 'noop'}),
                                msg.context['from_key'],
                                to_did=msg.context['from_did'],
                                from_key=msg.context['to_key'])
     assert agent.conductor.queues[msg.context['from_key']].qsize() == 2
Ejemplo n.º 6
0
 async def respond(agent, msg):
     logger.info('got ping, sending pong should queue message')
     pong = Message({'@type': pong_type})
     await agent.send(pong,
                      msg.context['from_key'],
                      to_did=msg.context['from_did'],
                      from_key=msg.context['to_key'])
     logger.info('sent pong to queue, probably')
     logger.info('queue up a noop')
     await agent.send(Message({'@type': Noop.TYPE}),
                      msg.context['from_key'],
                      to_did=msg.context['from_did'],
                      from_key=msg.context['to_key'])
     assert agent.conductor.pending_queues[
         msg.context['from_key']].qsize() == 2
Ejemplo n.º 7
0
 async def respond(agent, msg):
     logger.info('got ping')
     pong = Message({'@type': pong_type})
     await agent.send(pong,
                      msg.context['from_key'],
                      to_did=msg.context['from_did'],
                      from_key=msg.context['to_key'])
Ejemplo n.º 8
0
    def receive_file(self, filename: str, rng: Tuple[int, int], owner: tuple):
        # telling the nodes we NEED a file, therefore idx=-1 and data=None.
        msg = FileCommunication(self.name, owner[0], filename, rng)
        temp_s = create_socket(give_port())
        self.send_datagram(temp_s, msg, owner[1])
        print(f"Node {self.name} has sent the start-of-transfer message to "
              f"{owner[0]}.")

        while True:
            data, addr = temp_s.recvfrom(BUFFER_SIZE)
            dg: UDPDatagram = crypto_unit.decrypt(data)

            msg = Message.decode(dg.data)
            # msg now contains the actual bytes of the data for that file.

            # TODO some validation
            if msg["filename"] != filename:
                print(f"Wanted {filename} but received {msg['range']} range "
                      f"of {msg['filename']}")
                return

            if msg["idx"] == -1:
                print(f"Node {self.name} received the end-of-transfer message "
                      f"from {owner[0]}.")
                free_socket(temp_s)
                return

            self.received_files[filename].append(msg)
Ejemplo n.º 9
0
async def test_http_return_route(ping_pong_agents, message):
    (alice, alice_did, alice_vk, bob, bob_did, bob_vk) = ping_pong_agents

    ping = Message(message)
    await alice.conductor.send(ping, bob_vk, to_did=bob_did, from_key=alice_vk)
    await asyncio.wait_for(alice.ponged.wait(), 20)
    assert alice.ponged.is_set()
Ejemplo n.º 10
0
 async def respond(agent, msg):
     print('got ping')
     pong = Message({'@type': 'pong'})
     await agent.conductor.send(pong,
                                msg.context['from_key'],
                                to_did=msg.context['from_did'],
                                from_key=msg.context['to_key'])
Ejemplo n.º 11
0
async def test_module_routing_explicit_def():
    """ Test that routing to a module works. """
    from module import route_def

    agent = Agent()
    called_event = asyncio.Event()

    @module
    class TestModule():
        DOC_URI = ''
        PROTOCOL = 'test_protocol'
        VERSION = '1.0'

        routes = {}

        @route_def(routes, 'test_protocol/1.0/testing_type')
        async def route_gets_called(self, agent, msg, **kwargs):
            kwargs['event'].set()

    mod = TestModule()
    agent.route_module(mod)

    test_msg = Message({
        '@type': 'test_protocol/1.0/testing_type',
        'test': 'test'
    })
    await agent.handle(test_msg, event=called_event)

    assert called_event.is_set()
Ejemplo n.º 12
0
 def handle_node(self, data, addr):
     dg = crypto_unit.decrypt(data)
     message = Message.decode(dg.data)
     message_mode = message['mode']
     if message_mode == modes.HAVE:
         self.add_uploader(message, addr)
     elif message_mode == modes.NEED:
         self.search_file(message, addr)
     elif message_mode == modes.EXIT:
         self.exit_uploader(message, addr)
Ejemplo n.º 13
0
async def test_http_return_route_no_endpoint(connected_client_server_agents):
    (alice, alice_did, alice_vk, bob, bob_did,
     bob_vk) = connected_client_server_agents

    alice.ponged = asyncio.Event()

    @bob.route(ping_type)
    async def respond(agent, msg):
        logger.info('got ping, sending pong should queue message')
        pong = Message({'@type': pong_type})
        await agent.send(pong,
                         msg.context['from_key'],
                         to_did=msg.context['from_did'],
                         from_key=msg.context['to_key'])
        logger.info('sent pong to queue, probably')
        logger.info('queue up a noop')
        await agent.send(Message({'@type': Noop.TYPE}),
                         msg.context['from_key'],
                         to_did=msg.context['from_did'],
                         from_key=msg.context['to_key'])
        assert agent.conductor.pending_queues[
            msg.context['from_key']].qsize() == 2

    @alice.route(Noop.TYPE)
    @bob.route(Noop.TYPE)
    async def noop(agent, msg):
        logger.info(Noop.TYPE)
        pass

    @alice.route(pong_type)
    async def got_pong(agent, msg):
        logger.info('got pong')
        agent.ponged.set()

    gathered_agent_tasks = asyncio.gather(alice.start(), bob.start())

    # No return route, can't respond directly
    ping = Message({'@type': ping_type})
    await alice.send(ping, bob_vk, to_did=bob_did, from_key=alice_vk)

    logger.info('sending noop to pump bob\'s queue')
    noop = Noop(return_route=True)
    await alice.send(noop, bob_vk, to_did=bob_did, from_key=alice_vk)

    await asyncio.wait_for(alice.ponged.wait(), 5)

    logger.info('alice shutdown')
    await alice.shutdown()
    logger.info('bob shutdown')
    await bob.shutdown()
    gathered_agent_tasks.cancel()
    with suppress(asyncio.CancelledError):
        await gathered_agent_tasks

    assert alice.ponged.is_set()
Ejemplo n.º 14
0
 def save_message(self, message_body: dict, result: EventResult,
                  started: datetime, finished: datetime):
     try:
         message = Message(
             msg_id=message_body.get('message_id'),
             env=self.env_name,
             source=self.SOURCE_SYSTEM,
             object_id=result.related_object,
             display_context=result.display_context,
             level=message_body.get('priority'),
             msg=message_body,
             ts=message_body.get('timestamp'),
             received_ts=started,
             finished_ts=finished
         )
         self.inv.collections['messages'].insert_one(message.get())
         return True
     except Exception as e:
         self.inv.log.error("Failed to save message")
         self.inv.log.exception(e)
         return False
Ejemplo n.º 15
0
    def search(self, filename: str) -> dict:
        message = NodeToTracker(self.name, modes.NEED, filename)
        temp_s = create_socket(give_port())
        self.send_datagram(temp_s, message, TRACKER_ADDR)

        while True:
            data, addr = temp_s.recvfrom(BUFFER_SIZE)
            dg: UDPDatagram = crypto_unit.decrypt(data)
            if dg.src_port != TRACKER_ADDR[1]:
                raise ValueError(f"Someone other than the tracker with "
                                 f"port:{dg.src_port} sent {self.name} "
                                 f"the search datagram.")
            return Message.decode(dg.data)
Ejemplo n.º 16
0
 def start_listening(self):
     while True:
         data, addr = self.rec_s.recvfrom(BUFFER_SIZE)
         dg: UDPDatagram = crypto_unit.decrypt(data)
         msg = Message.decode(dg.data)
         if "size" in msg.keys() and msg["size"] == -1:
             # meaning someone needs the file size
             self.tell_file_size(dg, msg)
         elif "range" in msg.keys() and msg["data"] is None:
             print(f"Node {self.name} received the start-of-transfer "
                   f"message from Node {msg['src_name']}.")
             self.send_file(msg["filename"], msg["range"], msg["src_name"],
                            dg.src_port)
Ejemplo n.º 17
0
    def ask_file_size(self, filename: str, owner: tuple) -> int:
        # size == -1 means asking the size
        message = SizeInformation(self.name, owner[0], filename)
        temp_s = create_socket(give_port())
        self.send_datagram(temp_s, message, owner[1])

        while True:
            data, addr = temp_s.recvfrom(BUFFER_SIZE)
            dg: UDPDatagram = crypto_unit.decrypt(data)

            # TODO some validation

            free_socket(temp_s)
            return Message.decode(dg.data)["size"]
Ejemplo n.º 18
0
 def keep_message(self, doc, check_result, error_level=None):
     is_link = 'link_type' in doc
     msg_id = check_result['id']
     obj_id = 'link_{}_{}'.format(doc['source_id'], doc['target_id']) \
         if is_link \
         else doc['id']
     obj_type = 'link_{}'.format(
         doc['link_type']) if is_link else doc['type']
     display_context = obj_id if is_link \
         else doc['network_id'] if doc['type'] == 'port' else doc['id']
     level = error_level if error_level\
         else ERROR_LEVEL[check_result['status']]
     dt = datetime.datetime.utcfromtimestamp(check_result['executed'])
     message = Message(msg_id=msg_id,
                       env=self.env,
                       source=SOURCE_SYSTEM,
                       object_id=obj_id,
                       object_type=obj_type,
                       display_context=display_context,
                       level=level,
                       msg=check_result,
                       ts=dt)
     collection = self.inv.collections['messages']
     collection.insert_one(message.get())
Ejemplo n.º 19
0
    def start(self):
        pygame.init()

        self.level_manager = LevelManager(self.message_bus)
        self.event_manager = EventManager(self.message_bus)
        self.entity_manager = EntityManager(self.message_bus)
        self.screen_manager = ScreenManager(self.message_bus)
        self.debug_manager = DebugManager(self.message_bus)

        self.message_bus.subscribe(self)
        self.message_bus.subscribe(self.level_manager)
        self.message_bus.subscribe(self.event_manager)
        self.message_bus.subscribe(self.entity_manager)
        self.message_bus.subscribe(self.screen_manager)
        self.message_bus.subscribe(self.debug_manager)

        self.message_bus.post_message(Message("LOAD_LEVEL", "level_one"))

        self.clock = pygame.time.Clock()
        self.fps = 60
        self.running = True

        self.update()
Ejemplo n.º 20
0
async def test_module_routing_no_matching_version():
    """ Test that routing to a module works. """
    agent = Agent()
    called_event = asyncio.Event()

    @module
    class TestModule():
        DOC_URI = ''
        PROTOCOL = 'test_protocol'
        VERSION = '1.0'

        async def testing_type(self, agent, msg, *args, **kwargs):
            kwargs['event'].set()

    mod = TestModule()
    agent.route_module(mod)

    test_msg = Message({
        '@type': 'test_protocol/3.0/testing_type',
        'test': 'test'
    })
    with pytest.raises(NoRegisteredRouteException):
        await agent.handle(test_msg, event=called_event)
Ejemplo n.º 21
0
async def test_module_routing_simple():
    """ Test that routing to a module works. """
    agent = Agent()
    called_event = asyncio.Event()

    @module
    class TestModule():
        DOC_URI = ''
        PROTOCOL = 'test_protocol'
        VERSION = '1.0'

        async def testing_type(self, agent, msg, *args, **kwargs):
            kwargs['event'].set()

    mod = TestModule()
    agent.route_module(mod)

    test_msg = Message({
        '@type': 'test_protocol/1.0/testing_type',
        'test': 'test'
    })
    await agent.handle(test_msg, event=called_event)

    assert called_event.is_set()
Ejemplo n.º 22
0
    def emit(self, record):
        # Try to invoke InventoryMgr for logging
        if not self.inv:
            try:
                self.inv = InventoryMgr()
            except:
                return

        # make sure we do not try to log to DB when DB is not ready
        if not (self.inv.is_db_ready()
                and 'messages' in self.inv.collections):
            return

        # make ID from current timestamp
        now = datetime.datetime.utcnow()
        d = now - datetime.datetime(1970, 1, 1)
        timestamp_id = '{}.{}.{}'.format(d.days, d.seconds, d.microseconds)
        source = self.SOURCE_SYSTEM

        message = Message(msg_id=timestamp_id, env=self.env, source=source,
                          msg=Logger.formatter.format(record), ts=now,
                          level=record.levelname)
        if self.origin:
            message.extra['origin_id'] = (
                str(self.origin.origin_id)
                if self.origin.origin_id
                else None
            )
            message.extra['origin_type'] = (
                self.origin.origin_type.value
                if self.origin.origin_type
                else None
            )
            for extra_field in self.origin.extra:
                message.extra[extra_field] = getattr(self.origin, extra_field)

        self.inv.collections['messages'].insert_one(message.get())
Ejemplo n.º 23
0
    def update(self, dt: float):
        self.rect.x = self.entity_transform.x
        self.rect.y = self.entity_transform.y

        self.message_bus.post_message(Message("DRAW_ENTITY", self))
Ejemplo n.º 24
0
"""
@Author: Eduardo Rodríguez Sánchez
GLaDOS Voice
"""
from tts import voice
from status import gen_info
from messages.message import Message

message1 = Message("NONE", gen_info.moods)
print(message1.answers)

# text = voice.listen()
# voice.talk(text)
Ejemplo n.º 25
0
 def build_message(self, text='', action=None, parameters=None):
     message = Message(text)
     message.action = action or self.action
     message.parameters = parameters
     return message
Ejemplo n.º 26
0
 def update(self, dt: float, time: float):
     self.message_bus.post_message(Message("DRAW_TEXT",
                                           self.draw_fps(time)))
Ejemplo n.º 27
0
 def update(self, dt: float):
     for event in pygame.event.get():
         if event.type == KEYDOWN:
             if event.key == K_ESCAPE:
                 self.message_bus.post_message(Message("KB_PRESS_ESC"))
             if event.key == K_UP:
                 self.message_bus.post_message(Message("KB_PRESS_UP"))
             if event.key == K_DOWN:
                 self.message_bus.post_message(Message("KB_PRESS_DOWN"))
             if event.key == K_LEFT:
                 self.message_bus.post_message(Message("KB_PRESS_LEFT"))
             if event.key == K_RIGHT:
                 self.message_bus.post_message(Message("KB_PRESS_RIGHT"))
         if event.type == KEYUP:
             if event.key == K_ESCAPE:
                 self.message_bus.post_message(Message("KB_RELEASE_ESC"))
             if event.key == K_UP:
                 self.message_bus.post_message(Message("KB_RELEASE_UP"))
             if event.key == K_DOWN:
                 self.message_bus.post_message(Message("KB_RELEASE_DOWN"))
             if event.key == K_LEFT:
                 self.message_bus.post_message(Message("KB_RELEASE_LEFT"))
             if event.key == K_RIGHT:
                 self.message_bus.post_message(Message("KB_RELEASE_RIGHT"))
         elif event.type == QUIT:
             self.message_bus.post_message(Message("QuitGame"))
Ejemplo n.º 28
0
 def __init__(self, text, original):
     Message.__init__(self, text, channel=TWITTER)
     self.original = original
     self.username = self.original.user.screen_name
     self.reply_id = self.original.id
Ejemplo n.º 29
0
 async def pump_remote_queue(self, to_key, to_did, from_key):
     #TODO define noop somewhere else
     noop = Message({'@type': 'noop', '~transport': {'return_route': 'all'}})
     await self.send(noop, to_key, to_did=to_did, from_key=from_key)
Ejemplo n.º 30
0
 def write_message(self, sender, receiver, message, subject, creation_date, receiver_user):
     message = Message(sender, receiver, message, subject, creation_date)
     receiver_user.get_messages().add_message(message)