Exemple #1
0
    def _on_dlg_ok(self, e: Event) -> None:
        self._user = e.target.user_id

        OutStream.instance('').append(
            Message(type=Event.SIGN_IN,
                    user_id=e.target.user_id,
                    passwd=e.target.passwd))
Exemple #2
0
    def test_new_message(self):

        list_of_something = ["this", "is", "something"]
        m = Message("source_ip", "destination_ip", list_of_something)

        self.assertEqual(m.source, "source_ip")
        self.assertEqual(m.destination, "destination_ip")
        self.assertEqual(m.data, list_of_something)
Exemple #3
0
def login(tcpclient, token):
    model = pb.login_msg_pb2.LoginRequest()
    model.SessionToken = token
    model.BundleIdentifier = config.GAME["NAME"]
    req_data = model.SerializeToString()
    msg = Message(Message.MSG_TYPE_REQUEST,
                  route='Login/ReqLogin',
                  body=req_data)
    protocol_pack = Protocol(Protocol.PROTO_TYPE_DATA, msg.encode())
    return tcpclient.send(protocol_pack.pack())
Exemple #4
0
def request(tcpclient, type, router, data, pb):
    module = __import__(pb[0], globals(), locals(), [pb[1]])
    c = getattr(module, pb[1])()
    for k, v in data.items():
        setattr(c, k, v)

    req_data = c.SerializeToString()
    msg = Message(type, route=router, body=req_data)
    protocol_pack = Protocol(Protocol.PROTO_TYPE_DATA, msg.encode())
    return tcpclient.send(protocol_pack.pack())
Exemple #5
0
    def test_message_can_carry_partial_view(self):

        partial_view = PartialView("172.0.1.0")
        partial_view.add_peer_ip("172.0.1.1")
        partial_view.add_peer_ip("172.0.1.2")
        m = Message("source_ip", "destination_ip", partial_view)

        self.assertEqual(m.source, "source_ip")
        self.assertEqual(m.destination, "destination_ip")
        self.assertEqual(m.data, partial_view)
Exemple #6
0
 def send_message(self, destination_ip, path, data):
     destination = os.getenv('TEST_IP',
                             format_address(destination_ip, 5000))
     m = Message(format_address(self.ip, 5000), destination, data)
     logger.debug("Request", request=m.to_json())
     ret = requests.post(m.destination + '/' + self.api_version + '/' +
                         path,
                         json=m.to_json(),
                         timeout=5)
     logger.debug("Response", response=ret.content)
     return ret.content
 def send_next_ball(self, destination_ip):
     destination = os.getenv('TEST_IP',
                             format_address(destination_ip, 5001))
     m = Message(format_address(self.ip, 5001), destination, self.next_ball)
     logger.debug('I am sending next ball message.',
                  message=m.to_json(),
                  destination=destination)
     ret = requests.post(m.destination + '/' + self.api_version +
                         '/send-ball',
                         json=m.to_json(),
                         timeout=5)
     return ret.content
Exemple #8
0
    def test_new_message_to_json(self):

        partial_view = PartialView("172.0.1.0")
        partial_view.add_peer_ip("172.0.1.1")
        partial_view.add_peer_ip("172.0.1.2")
        m = Message("source_ip", "destination_ip", partial_view)

        # Transform it into json
        json_path = os.path.join(os.path.dirname(__file__), "message.json")
        with open(json_path) as json_file:
            d = json.load(json_file)
            self.assertEqual(m.to_json(), d)
            json_file.close()
Exemple #9
0
    def read(self):
        """
        Read a message from the Stack
        :return:
        """
        # Get the lock, to prevent changes in the stack while reading
        self.lock.acquire()

        # Read get the content
        message = json.loads(self.messages.pop(0))
        message = Message(message['message'], message['id'],
                          message['created_at'])

        # Release our lock
        self.lock.release()
        return message
Exemple #10
0
 def getTodaysColleagueNames(self, service, label):
     arrayOfEmail, emails, ids, msg, i = [], {}, [], Message(), 0
     ids.append(label["id"])
     allMessages = msg.ListMessagesWithLabels(service, "me", ids)
     if not allMessages:
         return False, False
     for m in allMessages:
         mail = msg.GetMessage(service, m["id"])
         headers = mail["payload"]["headers"]
         for header in headers:
             if (header["name"] == "Date"):
                 emails["Date"] = header["value"]
             if (header["name"] == "Subject"):
                 emails["Subject"] = header["value"]
         arrayOfEmail.append(emails)
     return arrayOfEmail, allMessages
Exemple #11
0
    def publish_message(self, message):
        """
        Publish a new message in the Queue
        :param message:
        :return:
        """
        # Create the new message
        message = Message(message)

        # Put it on the Stack
        self.stack.write(message)

        # Notify the consumers about this change
        self._notify_consumers()

        # Return to the caller, if something happens, the caller will get an exception
        return True
Exemple #12
0
    def send_sql_cur(self, cur):
        """
        sends the returned sql ref_cursor
        :param cur: sql function ref_cursor object result
        """
        description = None
        try:
            description = cur.description
            data = [i for i in cur]
            for row in data:

                idx = {str(i[0]): j for j, i in enumerate(cur.description)}

                msg = Message(msg=row[idx["MESSAGE"]],
                              m_type=row[idx["TYPE"]],
                              url=row[idx["URL"]],
                              reminder_date=row[idx["REMINDER_DATE"]],
                              reminder_msg=row[idx["REMINDER_MESSAGE"]])

                # TODO:Check nullable
                q_name = str(row[idx["NID"]])
                if (q_name != None or msg != None):
                    DBSubscriber.sender.send_msg(q_name, msg)

                    # #todo:prepare date
                    # reminder_date=str(msg.REMINDER_DATE).split("-")
                    #
                    # #Todo
                    # # :make reminder as regiser
                    # reminder=Reminder()
                    # DBSubscriber.reminderThread = threading.Thread(target=reminder.reminderAt,
                    #                                        args=(int(reminder_date[2]),
                    #                                              int(reminder_date[1]),
                    #                                              int(reminder_date[0]),
                    #                                              q_name,msg))
                    #
                    # DBSubscriber.reminderThread.start()

        except Exception as _:
            Logger.log.warning("Empty sql response returned. Ignoring sending")
            return
Exemple #13
0
    def read(self, socket: socket) -> List[Message]:
        msg_buffer = []

        try:
            self._in += socket.recv(4096)
        except:
            pass

        while len(self._in) > 4:
            msg_len = struct.unpack('>I', self._in[:4])[0]

            if len(self._in) >= (msg_len + 4):
                msg = json.loads(str(self._in[4:msg_len + 4].decode()))

                msg_buffer.append(Message(msg['type'], **msg['kwargs']))

                self._in = self._in[msg_len + 4:]
            else:
                break

        return msg_buffer
Exemple #14
0
def exchange_view(request):
    if request.method == 'POST':

        logger.info("ExchangeView")
        logger.debug("ExchangeView",
                     request=request,
                     partialView=cyclon.partialView)

        # 1) I cast the received json into a PartialView
        logger.debug(
            "ExchangeView: I cast the received json into a PartialView.")
        message = json.loads(request.body)
        received_partial_view = PartialView.from_dict(message.get('data'))

        # 2) I send a subset of my partial view no matter if the source ip is contained in it
        logger.debug(
            "ExchangeView: I send a subset of my partial view no matter if the source ip is contained in it."
        )
        to_send = cyclon.partialView.select_neighbors_for_reply()

        # 3) I merge current partial view with the one just received
        logger.debug(
            "ExchangeView: I merge current partial view with the one just received."
        )
        cyclon.partialView.merge(to_send, received_partial_view)
        logger.debug("ExchangeView", partialView=cyclon.partialView)

        m = Message(format_address(my_ip(), 5000), message.get('source'),
                    to_send)
        logger.debug("ExchangeView",
                     response=m.to_json(),
                     to=message.get('source'))
        return JsonResponse(m.to_json())

    else:
        return JsonResponse(
            {"error": {
                "message": "Only the POST method is allowed."
            }},
            status=403)
Exemple #15
0
 def toRole(entity: str, type_: str, text: str = '') -> None:
     OutStream.instance(entity).append(
         Message(type_, who='MUTED', text=text))
Exemple #16
0
 def askRole(entity: str, type_: str) -> None:
     OutStream.instance(entity).append(Message(type_, who='MUTED'))
Exemple #17
0
    def _on_msg_entered(self, text: str) -> str:
        OutStream.instance('').append(
            Message(type=Message.TEXT, who=self._user, text=text))

        return ''
 def __init__(self):
     self.msg = Message()