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())
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())
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
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()
class Test(object): def __init__(self, queue='rpc_queue'): self.queue = queue self.mes = Message() def __str__(self): pass def consume(self): self.mes.execute(self.queue)
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))
def get_conversation(df): messages = [] for index, (date_time, sender, text) in df.iterrows(): m = Message.from_args(date_time, sender, text) if '<Media omitted>' in text: m.set_media() messages.append(m) return Conversation(messages)
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)
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)
def handle_data(self): self.logger.debug("Handling incoming data") message = None if self.data: log_message = "Incoming discovery data from (" + str(self.address[0]) + ", " + str( self.address[1]) + "):\n<<<START>>>\n" + self.data.decode() + "\n<<<END>>>" self.logger.info(log_message) message = Message.to_object(self.data.decode()) return message
def respond_to_description_request(self): """ Handles the description request and sends a response. :return: """ self.logger.debug("Responding to description request") data = self.connection.recv(BUFFER_SIZE).decode('UTF-8') # print(self.node.name + " received a description request:\n" + data) log_message = "Description request received \n'" + data + "'" self.logger.info(log_message) with open(self.filename, 'a') as f: log_message = str(datetime.now()) + ": " + "Description request received" f.write(log_message) log_message = "\t\t" + data f.write(log_message) f.flush() if len(data) <= 0: return try: message = Message.to_object(data) except ValueError as e: self.logger.error(e.args[0]) # print(e.args) return # TODO: fix message type checking (message.to_object always assigns "2"!) self.logger.debug("Skipping Description request message type check; Responding to request.") # Create description message from node info response = Message(MessageType.description_response, self.node.name, self.node.address, Timestamp.create_timestamp(), self.node.service_list) # Convert message to json json_message = json.dumps(response.to_json()) # Encode message to utf-8 for sending through socket data = json_message.encode() self.connection.send(data) """
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)
class MessageTest(TestCase): def setUp(self): self.mes = Message() def api(self): response = self.mes.send(api='test') return response def lib(self): pass
def request_description(self): """ Request description of a node's services. Expects name of the node. """ if len(self.received_command) != 2: self.logger.error("Wrong argument count! Expected \"describe node_name\".") return node_name = self.received_command[1] address = self.peer_list.get_node_address(node_name) # TODO: send description request to address in peer_list self.logger.info("Sending description request to " + str(address)) # Create message and send it. message = Message(MessageType.description_request, node_name, address, Timestamp.create_timestamp()) data = message.to_json() data_str = json.dumps(data) self.output_socket.connect(address[0], address[1]) self.measurer.start_timer() self.output_socket.send(bytes(data_str, 'UTF-8')) response = self.output_socket.read() self.measurer.stop_timer() duration = self.measurer.get_last_duration() self.measurer.description_duration(self.node.name, duration) self.logger.info("Description request duration: {0}".format(duration)) response_str = response.decode('UTF-8') self.logger.debug(self.node.name + " received description response:\n" + response_str) if self.remote_socket: self.remote_socket.sendall(response) else: pass #print(response_str) update_message = Message.to_object(response_str) self.peer_list.update_node(node_name, update_message) #message = Message.to_object(response_str) return None
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
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
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
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
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
def __init__(self): self.msg = Message()
def setUp(self): self.mes = Message()
def __init__(self, queue='rpc_queue'): self.queue = queue self.mes = Message()
def toRole(entity: str, type_: str, text: str = '') -> None: OutStream.instance(entity).append( Message(type_, who='MUTED', text=text))
def askRole(entity: str, type_: str) -> None: OutStream.instance(entity).append(Message(type_, who='MUTED'))
class Helper: def __init__(self): self.msg = Message() def getExactName(self, person): if person.startswith(config.WORK_ANNIVERSARY_LABEL_HEADER): newPerson = person.replace(config.WORK_ANNIVERSARY_LABEL_HEADER, "") return newPerson.strip() elif person.startswith(config.BIRTHDAY_HEADER): newPerson = person.replace(config.BIRTHDAY_HEADER, "") return newPerson.strip() return person.strip() def getNamesFromSubject(self, subject): birthdayMates, workAnniversaryMates = [], [] allPeople = subject.rsplit(", ") if allPeople[0].startswith(config.BIRTHDAY_HEADER): if len(allPeople) > 1: for person in allPeople: birthdayMates.append(self.getExactName(person)) else: birthdayMates.append(self.getExactName(allPeople[0])) elif allPeople[0].startswith(config.WORK_ANNIVERSARY_LABEL_HEADER): if len(allPeople) > 1: for person in allPeople: workAnniversaryMates.append(self.getExactName(person)) else: workAnniversaryMates.append(self.getExactName(allPeople[0])) return birthdayMates, workAnniversaryMates """ Return array of person having birthday and having there work anniversary """ def getAllNamesFromHeaders(self, arr): print(arr) for item in arr: birthdayMates, workAnniversaryMates = self.getNamesFromSubject( item["Subject"]) return birthdayMates, workAnniversaryMates def sendBirthdayMails(self, service, mates): for mate in mates: toMySelf = self.msg.create_message( config.SENDER, config.SENDER, "!!!Sent Birthday Mail to %s" % (mate["name"].title()), "") message = self.msg.create_message( config.SENDER, mate["email"], config.BIRTHDAY_SUBJECT_LINE % (mate["name"].title()), "") self.msg.send_message(service, message) self.msg.send_message(service, toMySelf) def sendAnniversaryEmails(self, service, mates): for mate in mates: toMySelf = self.msg.create_message( config.SENDER, config.SENDER, "!!!Sent Work Anniversary Mail to %s" % (mate["name"].title()), "") message = self.msg.create_message( config.SENDER, mate["email"], config.WORK_ANNIVERSARY_SUBJECT_LINE % (mate["name"].title()), "") self.msg.send_message(service, toMySelf) self.msg.send_message(service, message) def plain(self, str): str = str.encode("utf-8") str = str.lower() str = " ".join(str.split()) return str def findEmailInAllPeoples(self, persons, allPeoples): mates = [] for person in persons: # print(person) for people in allPeoples["connections"]: # print(person.encode("utf-8"), people["names"][0]["displayName"].encode("utf-8"), search(person.encode("utf-8"), people["names"][0]["displayName"].encode("utf-8"))) if (self.plain(person) == self.plain( people["names"][0]["displayName"])): mates.append({ "email": self.plain(people["emailAddresses"][0]["value"]), "name": self.plain(person) }) return mates def sendEmailsToAll(self, service, birthdayMates, anniversaryMates, allPeoples): if len(birthdayMates): allMates = self.findEmailInAllPeoples(birthdayMates, allPeoples) self.sendBirthdayMails(service, allMates) if len(anniversaryMates): allMates = self.findEmailInAllPeoples(anniversaryMates, allPeoples) self.sendAnniversaryEmails(service, allMates) def markEmailAsRead(self, service, ids): if not ids: return for id in ids: self.msg.ModifyMessage(service, "me", id["id"].encode("utf-8"))
def _on_msg_entered(self, text: str) -> str: OutStream.instance('').append( Message(type=Message.TEXT, who=self._user, text=text)) return ''