Esempio n. 1
0
    def update_message(self, group_id, from_client_id, client_id, message,
                       message_id):
        self.model = Message().get(message_id)
        updated_at = datetime.now()
        self.model.updated_at = updated_at
        self.model.update()
        edited_message = self.model
        res_obj = message_pb2.MessageObjectResponse(
            id=edited_message.id,
            group_id=edited_message.group_id,
            from_client_id=edited_message.from_client_id,
            message=message,
            created_at=int(edited_message.created_at.timestamp() * 1000))
        if edited_message.client_id:
            res_obj.client_id = edited_message.client_id
        if edited_message.updated_at:
            res_obj.updated_at = int(edited_message.updated_at.timestamp() *
                                     1000)

        if client_id:
            res_obj.group_type = "peer"
        else:
            res_obj.group_type = "group"

        return res_obj
    def __init__(self, dronesSet: DronesSet, missionType: MissionType,
                 initialDronePos: dict, offsetDronePos: dict,
                 sendMessageCallable: Callable[[Message], None]):
        """Initialize the mission handler. Reject the mission if the droneSet
        is empty. Gives random colors to the drones ins the droneSet. Save
        the newly created mission object and saves it in the database.

          @param dronesSet: the set of drones participating in the mission.
          @param missionType: The type of the mission: real or fake. Fake is
          for demo purposes only. @param sendMessageCallable: the function to
          call to send mission pulses.
        """
        self.RANGE_SCALE: float = (
            missionType == 'argos') * self.ARGOS_SCALE + (
                missionType == 'crazyradio') * self.CRAZYRADIO_SCALE
        self.maxRange = (
            (missionType == 'argos') * self.ARGOS_MAX_RANGE +
            (missionType == 'crazyradio') * self.CRAZYRADIO_MAX_RANGE)
        drones: List[Drone] = list(dronesSet.getDrones().values())
        if len(drones) == 0:
            logging.info("Mission rejected: no drones")
            status: MissionStatus = 'rejected'
            sendMessageCallable(
                Message(type='missionPulse', data={'status': status}))
            return
        self.initialDronePos = initialDronePos
        self.offsetDronePos = offsetDronePos
        self.dronesSet = dronesSet
        self.sendMessageCallable = sendMessageCallable
        missionDrones: MissionDrones = {
            drone['name']: (CSS_PREDEFINED_COLORS[drone['name'].__hash__() %
                                                  len(CSS_PREDEFINED_COLORS)])
            for drone in drones
        }
        timestamp = getTimestamp()
        self.mission = Mission(
            id=f'Mission - {timestamp}',
            timestamp=timestamp,
            type=missionType,
            status='inProgress',
            drones=missionDrones,
            dronesPositions={drone['name']: []
                             for drone in drones},
            dronesPaths={drone['name']: []
                         for drone in drones},
            shapes=[],
            points=[])
        # DatabaseService.saveMission(self.mission['id'], self.mission)
        sendMessageCallable(Message(type='mission', data=self.mission))
        self.kdtree = kdtree.create(dimensions=2)
 def handlePositionAndBorders(self, droneName: str, position: Vec2,
                              points: List[Vec2]):
     """Add the new position of the drone as well as the position of the border it found to the mission.
     Saves the updated mission to the database.
       @param droneName: the name of the drone witch sent the informations.
       @param position: the 2D position of the drone.
       @param points: a list of 2D points
     """
     newMissionPoints = list(
         map(lambda point: MissionPoint(droneName=droneName, value=point),
             points))
     missionPulse = MissionPulse(id=self.mission['id'])
     if newMissionPoints:
         missionPulse['points'] = newMissionPoints
     lastPos = self.mission['dronesPositions'][droneName]
     if lastPos == [] or \
             math.dist([lastPos['x'], lastPos['y']], [position['x'], position['y']]) > self.MIN_POINTS_DIST:
         missionPulse['dronesPositions'] = {droneName: position}
         self.mission['dronesPositions'][droneName] = position
         self.mission['dronesPaths'][droneName].append(position)
     self.mission['points'] = [*self.mission['points'], *newMissionPoints]
     # DatabaseService.saveMission(self.mission['id'], self.mission)
     if len(missionPulse) > 1:
         self.sendMessageCallable(
             Message(type='missionPulse', data=missionPulse))
Esempio n. 4
0
 def _new_user_message(self, name):
     return Message(
         **{
             'message_type': MessageTypes.SYSTEM,
             'content': name,
             'system_type': SystemTypes.NEW_USER,
         })
Esempio n. 5
0
    def handle_handover(self, event):
        # from event payload determine the next node
        # convert this node into message
        # send this message to user
        # update state with new_node_id as current_node_id
        # respond with 200 ok status success
        current_node_id = self.state.get("current_node_id")
        next_node_data = AnaNode(current_node_id).get_next_node_data(self.message_data, self.state)
        next_node_id = next_node_data.get("node_id")

        self.state["current_node_id"] = next_node_id
        node_data = AnaNode(next_node_id).get_contents()
        data = AnaConverter(self.state).get_messages_data(node_data, self.message_data)
        messages_data = data.get("user_messages")

        self.meta_data["id"] = ""
        messages = [Message(meta=self.meta_data, data=data).trim() for data in messages_data]

        # message = Message(meta=self.meta_data, data=message_data).trim()
        user_response = Util.send_messages(messages=messages, sending_to="USER")


        if user_response:
            Util.update_state(meta_data=self.meta_data, state=self.state, is_handover=True)
            Util.log_events(meta_data=self.meta_data, state=self.state, events=data.get("publish_events", []))
        return []
Esempio n. 6
0
    def handle_no_agent_found(self, event):

        messages = []
        self.meta_data["id"] = ""

        message_text = "Apologies, our agents are busy at the moment"
        data = CustomMessage.get_simple_text(text=message_text)
        message = Message(meta=self.meta_data, data=data).trim()
        messages.append(message)

        message_text = "If you have already shared your information, we will get back to you"
        data = CustomMessage.get_simple_text(text=message_text)
        message = Message(meta=self.meta_data, data=data).trim()
        messages.append(message)

        user_response = Util.send_messages(messages=messages, sending_to="USER")
        return []
 def receive_message(self):
     message_length_bytes = self._recv_all(Entity.header_struct.size)
     message_length = Entity.header_struct.unpack(message_length_bytes)[0]
     message_bytes = self._recv_all(message_length)
     message = Message.from_bytes(message_bytes)
     self.log_info(
         f"Got a message {message} from {self.socket.getsockname()}")
     return message
Esempio n. 8
0
async def getNewMessages(days, hours):
    if days == None:
        days = 0
    else: 
        days = int(days)
    if hours == None:
        hours = 0
    else:
        hours = int(hours)
    print('Messages fetching started')
    client = getTelegramClient()
    await client.connect()
    connect(os.environ.get('MONGODB_URL_MESSAGES'), alias='Messages')
    connect(os.environ.get('MONGODB_URL_CHANNELS'), alias='Channels')
    connect(os.environ.get('MONGODB_URL_STATIC_LISTS'), alias='StaticChannels')
    connect(os.environ.get('MONGODB_URL_STATIC_LISTS'), alias='StaticTags')
    
    channels_config = getJSONdata(channels_config_path)
    channel_names = list(map(getName, StaticChannel.objects.all()))
    tags = list(map(getName, StaticTag.objects.all()))
    url_prefix = channels_config['url_prefix']
    db_channels = list(Channel.objects.all())

    for channel_name in channel_names:
        print(channel_name)
        last_date = datetime.now() - timedelta(days=days, hours=hours)
        index = getIndexNameInList(db_channels, channel_name)

        if index == -1:
            Channel(channel_name, last_date).save()
        else:
            last_date = db_channels[index].last_date


        messages = await getChannelMessages(
            client, 
            channel_name, 
            await getChannelMessageIdByDate(client, channel_name, last_date)
        )
        updateChannelLastDate.(channel_name)

        messages_to_db = []
        for message in messages:
            if message.text is None:
                continue
            message_to_db = Message(url=getMessageURL(url_prefix, channel_name, str(message.id)),
                                            text=message.message,
                                            date=message.date,
                                            channel=channel_name,
                                          
                                            salary=getSalary(message.message),
                                            tags=getTags(message.message, tags))
            if message_to_db:
                messages_to_db.append(message_to_db)
        if len(messages_to_db) != 0:
            Message.objects.bulk_create(messages_to_db)
    
    await client.disconnect()
Esempio n. 9
0
    def store_message(self,
                      message_id,
                      created_at,
                      group_id,
                      group_type,
                      from_client_id,
                      from_client_workspace_domain,
                      client_id,
                      message,
                      sender_message=b''):
        # init new message
        self.model = Message(
            id=message_id,
            group_id=group_id,
            from_client_id=from_client_id,
            from_client_workspace_domain=from_client_workspace_domain,
            client_id=client_id,
            message=message,
            created_at=created_at,
            sender_message=sender_message)
        self.model.add()
        # update group last message
        GroupChat(id=group_id,
                  last_message_at=created_at,
                  last_message_id=message_id).update()
        # response
        new_message = self.model.get(message_id)
        res_obj = message_pb2.MessageObjectResponse(
            id=new_message.id,
            group_id=new_message.group_id,
            group_type=group_type,
            from_client_id=new_message.from_client_id,
            from_client_workspace_domain=new_message.
            from_client_workspace_domain,
            message=message,
            created_at=int(new_message.created_at.timestamp() * 1000),
            sender_message=sender_message)
        if new_message.client_id:
            res_obj.client_id = new_message.client_id
        if new_message.updated_at:
            res_obj.updated_at = int(new_message.updated_at.timestamp() * 1000)

        res_obj.client_workspace_domain = get_owner_workspace_domain()

        return res_obj
Esempio n. 10
0
def index():
    messages = Message.query.all()
    if not messages:
        message = Message(text="Hello World")
        db.session.add(message)
        db.session.commit()
        messages.append(message)

    return jsonify([message.text for message in messages])
Esempio n. 11
0
    def stopMission():
        """Stops the current mission and send to the client th emessage to do so.

        """
        CrazyradioController.sendMessage(
            Message(type='stopMission', data={"name": "*"}))
        if CrazyradioController.missionHandler is not None:
            CrazyradioController.missionHandler.endMission()

        CrazyradioController.missionHandler.endMission()
def add_message(receiver: str):
    try:
        message_json = request.get_json()
        message = Message(creation_date=datetime.utcnow(),
                          receiver=receiver,
                          **message_json)
        message.save()
        return make_response()
    except BadRequest:
        return abort(HTTPStatus.BAD_REQUEST, description="Bad request")
    except FieldDoesNotExist:
        return abort(HTTPStatus.BAD_REQUEST,
                     description="One or more fields are incorrect")
    except ValidationError:
        return abort(HTTPStatus.BAD_REQUEST,
                     description="One or more fields are not valid")
    except Exception as error:
        logging.error(error)
        return abort(HTTPStatus.INTERNAL_SERVER_ERROR)
Esempio n. 13
0
    def sendAllRobotsStatus(socket) -> None:
        """Send all the information of every saved drones to the socket.

          @param socket: the socket to send the info to.
        """
        logging.info('Sending all robots status to new Dashboard client')
        drones: List[Drone] = CommunicationService().getAllDrones()
        for drone in drones:
            DashboardController.sendMessageToSocket(
                socket, Message(type="pulse", data=drone))
Esempio n. 14
0
    def onClientConnect(client: CrazyradioClient) -> None:
        """Called by a client when it connects to its interface.

          @param client: the client witch called the function.
        """
        logging.log(SUCCESS_LEVEL_NUM,
                    f'New Crazyradio client connected on uri {client.uri}')
        newDrone = Drone(name=client.uri, timestamp=getTimestamp())  # noqa
        CrazyradioController.dronesSet.setDrone(client.uri, newDrone)
        CommunicationService().sendToDashboardController(
            Message(type="pulse", data=newDrone))
def delete_message(receiver: str, message_id: str):
    try:
        fetched_messages = Message.objects(receiver=receiver, id=message_id)
        if not fetched_messages:
            print(fetched_messages)
            return Response("", status=HTTPStatus.NOT_FOUND)
        fetched_messages.delete()
        return make_response()
    except Exception as error:
        logging.error(error)
        return abort(HTTPStatus.INTERNAL_SERVER_ERROR)
 def emit(self, record: logging.LogRecord) -> None:
     logEntry = self.format(record)
     CommunicationService().sendToDashboardController(
         Message(
             type='loadProjectLog',
             data=LoadProjectLog(
                 log=logEntry,
                 type=DashboardLogger.getDashBoardLevelName(record),
                 timestamp=int(record.created)
             )
         )
     )
Esempio n. 17
0
    def onClientDisconnect(client: CrazyradioClient) -> None:
        """Called by a client when it disconnects from its interface. It send
        a message to the dashboards to inform the disconnection only if the
        server is running.

          @param client: the client witch called the function.
        """
        logging.info(f'Crazyradio client disconnected from uri {client.uri}')
        if CrazyradioController.running:
            CrazyradioController.clients.remove(client)
            CommunicationService().sendToDashboardController(
                Message(type="disconnect", data={"name": client.uri}))
    def stopMission(self):
        """Force stop the mission and register it as failed.

        """
        status: MissionStatus = 'failed'
        missionPulse = MissionPulse(
            id=self.mission['id'],
            status=status,
        )  # noqa
        self.mission['status'] = status
        DatabaseService.saveMission(self.mission['id'], self.mission)
        self.sendMessageCallable(
            Message(type='missionPulse', data=missionPulse))
 def endMission(self):
     """End the mission. Save the ’done’ status to the database and inform
     the dashboards.
     """
     # self.assignPointsToShapes()
     status: MissionStatus = 'done'
     missionPulse = MissionPulse(id=self.mission['id'],
                                 status=status,
                                 shapes=self.mission['shapes'])
     self.mission['status'] = status
     DatabaseService.saveMission(self.mission['id'], self.mission)
     self.sendMessageCallable(
         Message(type='missionPulse', data=missionPulse))
def get_messages(id_chat):
    """This function get a messages from a chat."""
    response = Response(json.dumps(
        json_error(ResponsesREST.INVALID_INPUT.value)),
                        status=ResponsesREST.INVALID_INPUT.value,
                        mimetype="application/json")
    if validator_id.is_valid({"id": id_chat}):
        get_message = Message()
        get_message.id_chat = id_chat
        result = get_message.get_messages_list()
        if result in (ResponsesREST.NOT_FOUND.value,
                      ResponsesREST.SERVER_ERROR.value):
            response = Response(json.dumps(json_error(result)),
                                status=result,
                                mimetype="application/json")
        else:
            list_chat = []
            for message_found in result:
                list_chat.append(message_found.json_message())
            response = Response(json.dumps(list_chat),
                                status=ResponsesREST.SUCCESSFUL.value,
                                mimetype="application/json")
    return response
Esempio n. 21
0
    def log_session_start(self, data):

        final_event_data = {}

        event_type = EventType.get_value("SESSION_STARTED")
        events = Event(type=event_type).trim()
        event_data = Message(meta=data, events=events).trim()

        final_event_data = {"meta": {"topic": "SESSION"}, "data": event_data}

        self.log_message(key="session", data=final_event_data)
        logger.info(
            f"SESSION_STARTED event logged with data {final_event_data}")
        return 1
Esempio n. 22
0
    def __construct_messages(self, meta_data, messages_data, sending_to):
        """
        This method constructs messages that are being sent
        """

        if sending_to is None:
            return []

        message_id = None
        if sending_to == "USER":
            if meta_data['senderType'] == SenderType.get_value("AGENT"):
                # If agent is the sender of incoming message, don't swap the sender and recipient
                recipient = meta_data["recipient"]
                sender = meta_data["sender"]
                sender_type = SenderType.get_value("ANA")
            else:
                recipient = meta_data["sender"]
                sender = meta_data["recipient"]
                sender_type = SenderType.get_value("ANA")
        elif sending_to == "AGENT":
            message_id = meta_data["id"]
            recipient = meta_data["recipient"]
            sender = meta_data["sender"]
            sender_type = SenderType.get_value("USER")

        previous_flow_id = self.state.get("previous_flow_id", "")
        current_flow_id = self.state.get("flow_id", "")

        outgoing_messages = []
        message_meta_data = MessageMeta(id=message_id,
                                        sender=sender,
                                        recipient=recipient,
                                        sessionId=meta_data["sessionId"],
                                        flowId=meta_data.get("flowId"),
                                        previousFlowId=previous_flow_id,
                                        currentFlowId=current_flow_id,
                                        responseTo=meta_data["id"],
                                        senderType=sender_type).trim()

        outgoing_messages = [
            Message(meta=message_meta_data, data=data).trim()
            for data in messages_data
        ]

        messages = [{
            "sending_to": sending_to,
            "message": message
        } for message in outgoing_messages]

        return messages
Esempio n. 23
0
    def sendAllMissions(socket) -> None:
        """Send all the saved mission in the database to the socket.

          @param socket: the socket to send the info to.
        """
        missions = DatabaseService.getAllMissions()
        currentMission = CommunicationService().getCurrentMission()
        if currentMission is not None:
            missions = [*missions, currentMission]
        logging.info(
            f'Sending all saved missions ({len(missions)} in total) to new '
            f'Dashboard client')
        for mission in missions:
            DashboardController.sendMessageToSocket(
                socket, Message(type="mission", data=mission))
Esempio n. 24
0
    def onControllerReceivedMessage(message: Message):
        """Decide what to do with the given message. It can start a mission
        or send the message as is to the clients.

          @param message: the message received.
        """
        if message['type'] == 'startMission':
            missionRequestData: dict = message['data']
            if missionRequestData['type'] == 'crazyradio':
                initialDronesPos = {}
                offsetDronePos = {} if 'dronesPositions' not in missionRequestData \
                    else missionRequestData['dronesPositions']
                for drone in CrazyradioController.dronesSet.getDrones().values(
                ):
                    initialDronesPos[drone['name']] = Vec2(
                        x=drone['position'][0], y=drone['position'][1])
                CrazyradioController.startMission(initialDronesPos,
                                                  offsetDronePos)
                if 'dronesPositions' not in missionRequestData:
                    CrazyradioController.missionHandler = None
        elif message['type'] == 'loadProject':
            loadProjectData = LoadProjectData(**message['data'])
            CrazyradioController.loadProject(loadProjectData)
        elif message['type'] == 'returnToBase':
            CrazyradioController.sendMessage(
                Message(type='returnToBase', data={'name': '*'}))
        elif message['type'] == 'stopMission':
            # TODO : Remove
            logging.info(f'Stopping mission {message}')
            if CrazyradioController.missionHandler is not None:
                CrazyradioController.missionHandler.stopMission()
                CrazyradioController.sendMessage(
                    Message(type='stopMission', data={'name': '*'}))
                CrazyradioController.missionHandler = None
        else:
            CrazyradioController.sendMessage(message)
    def onControllerReceivedMessage(message: Message):
        """Decide what to do with the given message. It can start a mission
        or send the message as is to the clients.

          @param message: the message received by the controller.
        """
        if message['type'] == 'startMission':
            missionRequestData: dict = message['data']
            if missionRequestData['type'] == 'argos':
                initialDronePos = {}
                offsetDronePos = {} if 'dronesPositions' not in missionRequestData \
                    else missionRequestData['dronesPositions']
                for drone in ArgosController.dronesSet.getDrones().values():
                    initialDronePos[drone['name']] = Vec2(
                        x=drone['position'][0], y=drone['position'][1])
                ArgosController.startMission(initialDronePos, offsetDronePos)
                if ArgosController.missionHandler.mission[
                        'status'] == 'inProgress':
                    for drone in ArgosController.dronesSet.getDrones().values(
                    ):
                        ArgosController.sendMessage(
                            Message(type='startMission',
                                    data={'name': drone['name']}))
            return
        elif message['type'] == 'returnToBase':
            for drone in ArgosController.dronesSet.getDrones().values():
                ArgosController.sendMessage(
                    Message(type='returnToBase', data={'name': drone['name']}))
        elif message['type'] == 'stopMission':
            if ArgosController.missionHandler is not None:
                ArgosController.missionHandler.stopMission()
                for drone in ArgosController.dronesSet.getDrones().values():
                    ArgosController.sendMessage(
                        Message(type='stopMission',
                                data={'name': drone['name']}))
                ArgosController.missionHandler = None
Esempio n. 26
0
    def handle_intent_to_handover(self, event):
        # from state get current_node_id
        # check if it's handofftoagent type node
        # process this node as combination node and get message data
        # fill meta and construct message
        # respond with this message
        node_id = self.state.get("current_node_id")
        node_contents = AnaNode(node_id).get_contents()
        data = CombinationProcessor(self.state).process_node(node_contents)
        messages = data.get("user_messages", [])
        message_data = {}
        if messages:
            message_data = messages[0]
        message = Message(meta=self.meta_data, data=message_data).trim()

        return [message]
    def onClientDisconnect(client: ArgosClient) -> None:
        """Called by a client when it disconnects from its socket. It send a
        message to the dashboards to inform the disconnection only if the
        server is running.

          @param client: the client witch called the function.
        """
        logging.info(f'ARGoS client disconnected from socket {client.socket}')
        if ArgosController.running:
            drones = ArgosController.dronesSet.getDrones()
            for drone in drones:
                CommunicationService().sendToDashboardController(
                    Message(type="disconnect", data={"name": drone}))
        ArgosController.client = None
        ArgosController.dronesSet = DronesSet()
        if ArgosController.missionHandler is not None:
            ArgosController.missionHandler.stopMission()
            ArgosController.missionHandler = None
Esempio n. 28
0
    def startMission(initialDronePos: dict, offsetDronePos: dict):
        """Start a mission. Order drones to takeoff and initialize a mission
        handler.

          @param initialDronePos: the drone position at the moment of the mission creation.
          @param offsetDronePos: the drone position offset given by the dashboard.
        """
        CrazyradioController.sendMessage(
            Message(type='startMission', data={"name": "*"}))
        if CrazyradioController.missionHandler is not None:
            CrazyradioController.missionHandler.endMission()

        CrazyradioController.missionHandler = MissionHandler(
            dronesSet=CrazyradioController.dronesSet,
            missionType='crazyradio',
            initialDronePos=initialDronePos,
            offsetDronePos=offsetDronePos,
            sendMessageCallable=lambda m: CommunicationService(
            ).sendToDashboardController(m))
    def startMission(initialDronePos: dict, offsetDronePos: dict):
        """Start a mission. Order drones to takeoff and initialize a mission
        handler.

          @param initialDronePos: the drone position at the moment of the mission creation.
          @param offsetDronePos: the drone position offset given by the dashboard.
        """
        logging.info("START MISSION")
        for drone in ArgosController.dronesSet.getDrones():
            ArgosController.sendMessage(
                Message(type='startMission', data={"name": drone}))

        ArgosController.missionHandler = MissionHandler(
            dronesSet=ArgosController.dronesSet,
            missionType='argos',
            initialDronePos=initialDronePos,
            offsetDronePos=offsetDronePos,
            sendMessageCallable=lambda m: CommunicationService(
            ).sendToDashboardController(m))
Esempio n. 30
0
    def __handle_delivery_events(self, event):
        sender = SenderType.get_name(self.meta_data["senderType"])

        sending_to = None

        if sender == "AGENT":
            sending_to = "USER"
        elif sender == "USER":
            node_key = self.state.get("current_node_id")
            is_agent_node = AnaNode(node_key).check_if_agent_node()
            if is_agent_node:
                sending_to = "AGENT"

        logger.debug(f"Typing event forwarded to {sending_to} meta {self.meta_data} event {event}")

        message = Message(meta=self.meta_data, events=[event]).trim()

        Util.send_messages(messages=[message], sending_to=sending_to)
        return []