예제 #1
0
def store_message_in_db():

    try:
        data = request.json

        # validate post inputs
        MessageSchema().load(data)

        sender = data['sender']
        receiver = data['receiver']
        message = data['message']
        subject = data['subject']

        new_message = Message(sender=sender,
                              receiver=receiver,
                              message=message,
                              subject=subject)

        db.session.add(new_message)
        db.session.commit()

        return message_schema.dump(new_message)

    except ValidationError as err:
        return err.messages
예제 #2
0
def message_create():
    # Retrieve a particular users workhistorys

    username_of_jwt = get_jwt_identity()
    user_sender_object = User.query.get(username_of_jwt)
    user_receiver_object = User.query.get(request.json["username_of_receiver"])

    if not (user_sender_object or user_receiver_object):
        return abort(401, description="A user is invalid")

    if not request.json["content"]:
        return abort(401, description="Must have non-empty content")

    # user_id = get_jwt_identity()
    message_object_from_fields = Message()

    message_object_from_fields.username_of_sender = username_of_jwt
    message_object_from_fields.username_of_receiver = request.json[
        "username_of_receiver"]
    message_object_from_fields.content = request.json["content"]

    db.session.add(message_object_from_fields)

    db.session.commit()
    return jsonify(message_schema.dump(message_object_from_fields))
예제 #3
0
def first_message_to_user(content, email, device):
    try:
        user = db.session.query(UserModel).filter(
            UserModel.email == email).first()
        if user is None:
            raise e_account.UserNotFound
        elif not device.circle.has_member(user):
            raise e_cirle.UserNotPartOfCircle
        conversation = Conversation(device_access=True)
        conversation.circle = device.circle
        conversation.name = "NewConversation"
        link = UserToConversation(privilege="ADMIN")
        link.user = user
        link.conversation = conversation
        message = Message(content=content["text_message"]
                          if "text_message" in content else "",
                          is_user=False)
        message.conversation = conversation
        message.device = device
        media_list = []
        if "files" in content:
            for file in content["files"]:
                media = Media()
                media.identifier = file
                MessageToMedia(message=message, media=media)
                db.session.commit()
                media_list.append(media.get_simple_content())
        db.session.commit()
        sockets.notify_user(user, False, 'conversation', {
            "conversation_id": conversation.id,
            "event": 'invite'
        })
        info_and_message = "[" + conversation.name + "] " + device.name + " : " + str(
            message.text_content)
        try:
            messenger_conversation_model_send(0, conversation,
                                              info_and_message)
        except Exception:
            pass
        try:
            hangout_conversation_model_send(0, conversation, info_and_message)
        except Exception:
            pass
        response = {
            "data": {
                "success": True,
                'media_list': media_list,
                'message_id': message.id
            },
            "status_code": 200
        }
    except (e_cirle.CircleException, e_account.AccountException) as exception:
        response = {
            "data": {
                "success": False,
                "message": exception.message
            },
            "status_code": exception.status_code
        }
    return response
예제 #4
0
    def provide_info(self, message):
        """
        This method is called by the remote user, it sends all the information that it has about the current devices
        connected
                {   "id": 112223,
                    "payload": "{\"type\": \"provide_info\",
                                "command": { "name":"fetch_all_drone_info"
                                }",
                    "sender": "communication_handler",
                    "to": "drone_handler",
                    "type": "drone"
                }
        """
        payload = message.payload
        info_command = payload["command"]
        name = info_command["name"]

        if name == "fetch_all_drone_info":
            r_list = []
            for drone in list(self.drones.keys()):
                r_list.append(drone.to_dict())
            result = json.dumps({"drones": r_list})

            new_message = Message("drone_handler", message.sender, "comms", {
                "type": "reply",
                "data": result
            })

            self.server.message_handler.handle_message(new_message)
예제 #5
0
 def setUp(self):
     neo_config.load_config()
     neo_config.set_project_variables()
     neo = NeoAPI(neo_config)
     self.api = neo.activate_testing()
     self.user1 = db.session.query(UserModel).filter(
         UserModel.email == "*****@*****.**").first()
     if self.user1 is None:
         self.user1 = UserModel(email="*****@*****.**",
                                password="******",
                                first_name="firstname",
                                last_name="lastname",
                                birthday="1995-12-12")
     self.user2 = db.session.query(UserModel).filter(
         UserModel.email == "*****@*****.**").first()
     if self.user2 is None:
         self.user2 = UserModel(email="*****@*****.**",
                                password="******",
                                first_name="firstname",
                                last_name="lastname",
                                birthday="1111-11-11")
     self.circle = Circle(name="TestMessageCreate")
     self.linkCircle = UserToCircle(user=self.user1, circle=self.circle)
     self.linkCircle2 = UserToCircle(user=self.user2, circle=self.circle)
     self.conversation = Conversation(circle=self.circle,
                                      name="TestMessageCreate")
     self.linkConversation = UserToConversation(
         user=self.user1, conversation=self.conversation, privilege="ADMIN")
     self.linkConversation2 = UserToConversation(
         user=self.user2, conversation=self.conversation)
     self.message = Message(link=self.linkConversation,
                            conversation=self.conversation,
                            content="1")
     self.message2 = Message(link=self.linkConversation,
                             conversation=self.conversation,
                             content="2")
     self.message3 = Message(link=self.linkConversation2,
                             conversation=self.conversation,
                             content="3")
     db.session.commit()
     self.token1 = authenticate_user(self.api, self.user1, "test")
     self.token2 = authenticate_user(self.api, self.user2, "test")
     self.tokenAdmin = authenticate_user(self.api,
                                         "*****@*****.**",
                                         "PapieNeo2019")
예제 #6
0
def send_message(user_from, user_to_username, msg_text):
    user_to = User.load_user_by_name(user_to_username)
    if user_to:
        message = Message()
        message.from_id = user_from.id
        message.to_id = user_to.id
        message.msg_text = msg_text
        return message.save_to_db()
    raise ValueError(f"No user '{user_to_username}' in the database.")
    def handle_utility(self, message):
        client = self.get_client_from_username(message.sender)
        seconds = int(round(time.time()))
        client.last_ping = seconds

        ping_payload = {"utility_group": "ping"}
        ping_message = Message("core", message.sender, MessageType.utility,
                               ping_payload)
        self.send_message_to_client(ping_message)
예제 #8
0
    def get_random_messages(self):
        time = datetime.now()

        for x in range(10):
            text = random_sentence(10)

            self.messages.append(Message(False, time, text, random.randint(1, 2) * 2))

            time = time + timedelta(days=random.randint(2, 30))
    def handle_ping(self, message):
        client = self.server.get_client_from_username(message.sender)
        client.update_last_ping()

        ping_payload = {"utility_group": "ping"}
        ping_message = Message("core", message.sender, MessageType.utility,
                               ping_payload)
        self.logger.debug("[handle_ping], replying ping message " +
                          str(ping_message))
        self.server.send_message_to_client(ping_message)
예제 #10
0
def get_input():
    global server
    while True:
        s = input()
        if s == "exit":
            print(log.server_closed + get_time())
            server.close()
            os._exit(1)
            break
        elif s == "send":  # This cmd is just for test
            sid = input("session_id?")
            title = input("title?")
            content = input("content?")
            img_url = input("img_url?")
            send_to(sid, Message(title, content, img_url))
        elif s == "send2all":
            title = input("title?")
            content = input("content?")
            img_url = input("img_url?")
            send_to_all(Message(title, content, img_url))
예제 #11
0
    async def on_message_delete(self, message: discord.Message):
        if message.author.bot or message.type == MessageType.new_member:
            return
        if len(message.content) == 0:
            return
        member = session.query(Member) \
            .filter(Member.ServerId == message.guild.id) \
            .filter(Member.MemberId == message.author.id).first()

        saveMessage = Message(member.Id, message.channel.id, message.content)
        session.add(saveMessage)
        session.commit()
예제 #12
0
 def setUp(self):
     neo_config.load_config()
     neo_config.set_project_variables()
     neo = NeoAPI(neo_config)
     self.api = neo.activate_testing()
     self.user1 = db.session.query(UserModel).filter(
         UserModel.email == "*****@*****.**").first()
     if self.user1 is None:
         self.user1 = UserModel(email="*****@*****.**",
                                password="******",
                                first_name="firstname",
                                last_name="lastname",
                                birthday="1995-12-12")
     self.user2 = db.session.query(UserModel).filter(
         UserModel.email == "*****@*****.**").first()
     if self.user2 is None:
         self.user2 = UserModel(email="*****@*****.**",
                                password="******",
                                first_name="firstname",
                                last_name="lastname",
                                birthday="1111-11-11")
     self.circle = Circle(name="Mamie")
     self.circle2 = Circle(name="test")
     self.linkCircle = UserToCircle(user=self.user1,
                                    circle=self.circle,
                                    privilege="ADMIN")
     self.linkCircle2 = UserToCircle(user=self.user2, circle=self.circle)
     self.conversation = Conversation("test")
     self.conversation.circle = self.circle
     self.conversation.device_access = True
     self.device = Device(name="Papie")
     self.device2 = Device(name="test")
     self.device2.circle = self.circle2
     self.device2_password = self.device2.get_pre_activation_password()
     self.device2.activate(self.device2.key)
     self.device.circle = self.circle
     self.device_password = self.device.get_pre_activation_password()
     self.device.activate(self.device.key)
     self.message = Message(is_user=False)
     self.message.conversation = self.conversation
     self.message.device = self.device
     db.session.commit()
     self.token1 = authenticate_user(self.api, self.user1, "test")
     self.token2 = authenticate_user(self.api, self.user2, "test")
     self.device_token = authenticate_device(self.api, self.device,
                                             self.device_password)
     self.device2_token = authenticate_device(self.api, self.device2,
                                              self.device2_password)
     self.tokenAdmin = authenticate_user(self.api,
                                         "*****@*****.**",
                                         "PapieNeo2019")
예제 #13
0
    def post(self):
        sender = username = self.get_cookie("username")
        receiver = self.request.get('receiver')
        title = self.request.get('title')
        content = self.request.get('content')

        if receiver and title and content:
            msg = Message(sender=sender,
                          receiver=receiver,
                          title=title,
                          content=content)
            msg.put()
            self.redirect('/')
        else:
            self.response.out.write("Error in Messages.post()")
예제 #14
0
    def createMessage(self, info):
        foreignID = info['foreignID']
        description = info['description'].replace('\'', '\\\'').replace('\"', '\\\"')
        # 用以区分消息类型 1 代表钱包消息, 2代表收藏消息, 3代表买家评论消息, 4代表邀请码消息
        tag = info['tag']
        # 以下三个参数只有评论消息才有, 否则为'-1'
        fromUserID = info['fromUserID']
        toUserID = info['toUserID']

        messageID = self.generateID(foreignID + description)
        message = Message(messageID=messageID, foreignID=foreignID,
                          fromUserID=fromUserID, toUserID=toUserID,
                          description=description, tag=tag)
        db.session.add(message)
        return (True, messageID)
    def accept_connections(self):
        """
        This method accepts connections, however this method is called by check for messages, if the own core socket
        is readable then this method is called to accept the incoming connection, later on new socket is created!
        This method accepts the connection without authenticating it.
        :return: nothing
        """
        conn, address = self.socket_layer.socket.accept()
        # If set blocking is 0 core does not wait for message and this try block fails.
        conn.setblocking(1)

        # This is a special message since it is authentication
        json_string = self.socket_layer.read_message_from_connection(
            conn).decode("utf-8")

        print("Accepting connection " + str(json_string))

        self.logger.info("Accepting connection " + str(json_string))

        # new_message = Message.json_string_to_message(json_string)
        json_package = json.loads(json_string)
        username = json_package["username"]
        password = json_package["password"]
        # TODO Check client credidentals

        # hostname = json_package["hostname"]
        # host_system_username = json_package["host_system_username"]

        if self.all_clients.get(username, None) is not None:
            self.logger.info("User reconnected in short time " + str(username))
            # This means that the client reconnected before we noticed it
            old_client = self.all_clients[username]
            self.remove_client(old_client)

        new_client = socket_client(username, password, conn)

        # we need set blocking 0 so that select works in server_controller. With this sockets will not block....
        conn.setblocking(1)
        self.all_connections.append(conn)
        # Put the newly connected client to the list
        self.all_clients[username] = new_client
        # Push a message to the queue to notify that a new client is connected
        client_connected_message = Message(username, "core", "event",
                                           "Connected")

        self.inbox_queue.put(client_connected_message)
예제 #16
0
def new_thread_message():
    sender_public_id = request.args.get('sender_public_id')
    receiver_public_id = request.args.get('receiver_public_id')
    room_id = request.args.get('room_id')

    print(sender_public_id)
    print(receiver_public_id)
    print(room_id)

    user1 = User.query.filter_by(public_id=sender_public_id).first()
    user2 = User.query.filter_by(public_id=receiver_public_id).first()

    user1_id = user1.id
    user2_id = user2.id

    print(user1_id)
    print(user2_id)
    print(room_id)

    thread = Thread.query.filter_by(user1_id=user1_id, user2_id=user2_id).first()
    if thread is None:
        thread = Thread.query.filter_by(user2_id=user1_id, user1_id=user2_id).first()

    if thread is None:
        thread = Thread(user1_id, user2_id)
        room = Room.query.filter_by(id=room_id).first()
        room.threads.append(thread)

    args_data = request.get_json()

    message_data = args_data['message']
    print(message_data)

    format_date = datetime.strptime(message_data['timestamp'], '%d/%m/%Y %H:%M')

    sender = User.query.filter_by(public_id=sender_public_id).first()

    thread.messages.append(Message(False, format_date, message_data['text'], sender.id))

    for i in thread.messages:
        print(i.to_dict())

    db.session.commit()

    return jsonify({'message': 'SUCCESS'})
예제 #17
0
def handle_conversation_payload(message_payload):
    try:
        payload = jwt.decode(message_payload, SECRET_KEY)
        try:
            print(message_payload)
            link = db.session.query(UserToConversation).filter(UserToConversation.id == payload["link_id"] and
                                                               UserToConversation.user_id == payload["user_id"]).first()
            message = Message(content=payload["message_text"])
            message.link = link
            message.conversation = link.conversation
            db.session.commit()
            return "Votre message a été envoyé avec succès"
        except Exception as e:
            return "Une erreur est survenue : " + str(e)
    except jwt.ExpiredSignatureError:
        return 'Message expiré, renvoyez le message'
    except jwt.InvalidTokenError:
        return 'Message expiré, renvoyez le message'
예제 #18
0
 def createOAMessage(self, info):
     foreignID = info['foreignID']
     description = info['description']
     # 用以区分消息类型 1 代表推送消息
     tag = info['messageTag']
     fromUserID = info['userID']
     toUserID = info['toUserID']
     messageID = self.generateID(foreignID + description)
     createTime = datetime.now()
     try:
         message = Message(messageID=messageID, foreignID=foreignID, fromUserID=fromUserID,
                           toUserID=toUserID, description=description, tag=tag,
                           createTime=createTime)
         db.session.add(message)
         db.session.commit()
         return (True, messageID)
     except Exception as e:
         print e
         errorInfo = ErrorInfo['TENDER_02']
         errorInfo['detail'] = str(e)
         db.session.rollback()
         return (False, errorInfo)
예제 #19
0
def handle_conversation_payload(message_payload):
    try:
        payload = jwt.decode(message_payload, SECRET_KEY)
        try:
            link = db.session.query(UserToConversation).filter(
                UserToConversation.id == payload["link_id"],
                UserToConversation.user_id == payload["user_id"]).first()
            user = db.session.query(User).filter(
                User.id == payload["user_id"]).first()
            if len(payload["images"]) == 0:
                message = Message(content=payload["message_text"])
                message.link = link
                message.conversation = link.conversation
                db.session.commit()
                emit('message', {
                    'conversation_id': message.conversation_id,
                    'message': message.get_simple_json_compliant_content(),
                    'time': message.sent.isoformat(),
                    'sender': user.get_simple_json_compliant_content(),
                    'media_list': [],
                    'status': 'done'
                },
                     room='conversation_' + str(message.conversation_id),
                     namespace='/')
                message.conversation.mobile_notification(
                    title="Message",
                    body=user.first_name + " vous à envoyer un message.")
            else:
                push_images_to_api(user=user,
                                   conv_id=link.conversation.id,
                                   message=payload["message_text"],
                                   attachment_images=payload["images"])
        except Exception as e:
            return "Une erreur est survenue : " + str(e)
    except jwt.ExpiredSignatureError:
        return 'Message expiré, renvoyez le message'
    except jwt.InvalidTokenError:
        return 'Message expiré, renvoyez le message'
예제 #20
0
def core_message_send(content, conversation_id, user):
    try:
        link = db.session.query(UserToConversation).filter(
            UserToConversation.conversation_id == conversation_id,
            UserToConversation.user_id == user.id).first()
        if link is None:
            raise e_conversation.ConversationNotFound
        message = Message(content=content["text_message"] if "text_message" in
                          content else "")
        message.conversation = link.conversation
        message.link = link
        media_list = []
        if "files" in content:
            for file in content["files"]:
                media = Media()
                media.identifier = file
                MessageToMedia(message=message, media=media)
                db.session.commit()
                media_list.append(media.get_simple_content())
        db.session.commit()
        response = {
            "data": {
                "success": True,
                'media_list': media_list,
                'message_id': message.id
            },
            "status_code": 200
        }
    except e_conversation.ConversationException as exception:
        response = {
            "data": {
                "success": False,
                "message": exception.message
            },
            "status_code": exception.status_code
        }
    return response
    def remove_client(self, client, reason=None):
        """
        This method removes the client from the core in a higher level, it creates the appropriate messages,
        logs the time stamp and such. In future mysql will also log sesion time here.
        :param client: the client object that is being removed from the core
        :param reason: will be implemented in future
        :return: nothing, literally nothing
        """
        total_session_time = datetime.datetime.now() - client.connection_time

        ColorPrint.print_message(
            "Warning", "remove_client", "kicking the client " +
            str(client.username) + " Reason " + str(reason))

        self.logger.warning("Kicking client  " + str(client.username) +
                            " Total Session Time " + str(total_session_time) +
                            " Reason " + str(reason))
        # cleaning up the sockets and such
        client_conn = client.socket_connection
        #TODO remove client from sql table
        try:
            self.all_clients.pop(client.username)

            self.all_connections.remove(client_conn)

            self.socket_layer.close_connection(client_conn)

        except Exception as e:
            # Probably client is already removed
            self.logger.error("[remove client] remove_client error " + str(e))
            self.logger.error("[remove client] " + str(traceback.format_exc()))

        client_disconnected_message = Message(
            "core", "core", "event",
            "Client Disconnected " + str(client) + " Reason " + str(reason))
        self.inbox_queue.put(client_disconnected_message)
def seed_db():

    from models.User import User
    from models.StudyHistory import StudyHistory
    from models.WorkHistory import WorkHistory
    from models.Certification import Certification
    from models.ResumeProject import ResumeProject
    from models.Meeting import Meeting
    from models.Message import Message
    from models.Connection import Connection
    from models.Post import Post
    from models.JobSalary import JobSalary
    from models.ITNews import ITNews
    from main import bcrypt
    from faker import Faker
    from random import randrange, choice

    from datetime import datetime

    now = datetime.now()

    faker = Faker()

    user_list = []

    # Create fake users

    for i in range(5):
        user = User()
        user.username = f"test{i}"
        user.first_name = faker.first_name()
        user.last_name = faker.last_name()
        user.created_at = now.strftime('%Y-%m-%d %H:%M:%S')
        user.email = f"test{i}@gmail.com"
        user.password = bcrypt.generate_password_hash("123456").decode("utf-8")
        user.mobile = faker.phone_number()
        user.city = faker.city()
        user.country = faker.country()
        user.dob = faker.date_of_birth()

        db.session.add(user)
        user_list.append(user)
    
    

    db.session.commit()

    studyhistory_list = []
    
    qualifications = ['bachelor', 'master', 'honours']
    institutions = ['rmit', 'latrobe', 'monash']
    for i in range(20):

        studyhistory = StudyHistory()
        studyhistory.username = choice(user_list).username

        studyhistory.qualification_title = choice(qualifications)
        studyhistory.institution = choice(institutions)
        studyhistory.city = faker.city()
        studyhistory.country = faker.country()
        studyhistory.date_start = faker.date_of_birth()
        studyhistory.date_end = faker.date_of_birth()

        db.session.add(studyhistory)
        studyhistory_list.append(studyhistory)


    db.session.commit()

    company = ['nab', 'aws', 'microsoft']
    job_title = ['engineer', 'developer', 'architect']
    for i in range(20):

        workhistory = WorkHistory()

        workhistory.username = choice(user_list).username

        workhistory.job_title = faker.job()
        workhistory.company = choice(company)
        workhistory.city = faker.city()
        workhistory.country = faker.country()
        workhistory.date_start = faker.date_of_birth()
        workhistory.date_end = faker.date_of_birth()

        db.session.add(workhistory)


    cert_names = ['aws cloud practitioner', 'microsoft azure administrator', 'microsoft excel']
    descriptions = ['Expert', 'Advanced', 'Beginner']
    issuers = ['Microsoft', 'AWS', 'Google']

    for i in range(20):

        certification = Certification()

        certification.username = choice(user_list).username

        certification.cert_name = choice(cert_names)
        certification.description = choice(descriptions)
        certification.issuer = choice(issuers)
        certification.date_obtained = faker.date_of_birth()

        db.session.add(certification)


    resume_paths_list = ['file1', 'file2', 'file3']
    github_account_list = ['https://github.com/mrixon95', 'https://github.com/HarryTranAU/', 'https://github.com/ashley190']


    for i in range(20):

        resumeproject = ResumeProject()

        resumeproject.username = choice(user_list).username

        resumeproject.resume_path = choice(resume_paths_list)
        resumeproject.github_account = choice(github_account_list)

        db.session.add(resumeproject)


    qualifications = ['bachelor', 'master', 'honours']
    institutions = ['rmit', 'latrobe', 'monash']


    for i in range(20):

        meeting = Meeting()
        meeting.username = choice(user_list).username

        meeting.time_start = faker.date_of_birth()
        meeting.time_end = faker.date_of_birth()
        meeting.location = faker.city()
        meeting.subject = faker.word()
        meeting.description = faker.word()
        meeting.last_updated = faker.date_of_birth()

        db.session.add(meeting)

    db.session.commit()


    for i in range(5):

        message = Message()
        message.username_of_sender = user_list[i].username
        message.username_of_receiver = user_list[(i + 1) % 5].username
        message.content = faker.text()

        db.session.add(message)

    
    for i in range(5):

        connection = Connection()
        connection.username_of_requester = user_list[i % 5].username
        connection.username_of_confirmer = user_list[(i + 3) % 5].username
        connection.user_1_approved = True
        connection.user_2_approved = True
        connection.status = "confirmed"

        db.session.add(connection)



    for i in range(5):

        post = Post()
        post.username = user_list[i % 5].username
        post.content = faker.text()
        post.last_updated = faker.date_of_birth()
        
        db.session.add(post)

    
    for i in range(5):

        jobsalary = JobSalary()
        jobsalary.title = faker.job()
        jobsalary.lower_quartile = faker.random_int(30, 50)
        jobsalary.median_salary = faker.random_int(70, 120)
        jobsalary.upper_quartile = faker.random_int(150, 500)
        jobsalary.average_years_experience = faker.random_int(1, 10)

        db.session.add(jobsalary)

    for i in range(5):

        ITnews = ITNews()
        ITnews.article_link = faker.url()
        ITnews.photo_link = faker.image_url()
        ITnews.published_time = faker.past_date()

        db.session.add(ITnews)



    db.session.commit()
                for message in messages:
                    print(
                        f"From:{User.load_user_by_id(cur, message.from_id).username}\n Date: {message.creation_date}\n Message: {message.text}")

        else:
            print("Password incorrect")
elif args.send:
    if args.username is not None and args.password is not None:
        user = User.load_user_by_email(cur, args.username)
        hashed = user.hashed_password
        if check_password(args.password, hashed):
            if args.to is not None:
                recipient = User.load_user_by_email(cur, args.to)
                if recipient is not None:
                    if args.send is not None:
                        new_message = Message()
                        new_message.to_id = recipient.id
                        new_message.from_id = user.id
                        new_message.text = args.send
                        new_message.creation_date = datetime.now()
                        new_message.save_to_db(cur)
                        print(f"You send a message to {recipient.username}")
                    else:
                        print("Please enter a message")
                else:
                    print("There is no user with this mail")
        else:
            print("Password incorrect")
else:
    parser.print_help()
예제 #24
0
파일: main.py 프로젝트: scarlson/d20-tools
def captureMessage(a=None, b=None, c=None):
    '''
        Capture JSON messages between server and client
    '''
    Msg = Message(source=a, destination=b, content=c)
    Msg.put()
예제 #25
0
def init_default_content(p1, p2):
    user = db.session.query(User).filter(
        User.email == "*****@*****.**").first()
    user2 = db.session.query(User).filter(
        User.email == "*****@*****.**").first()
    if user is None and user2 is None:
        user = User(email="*****@*****.**",
                    password=p1,
                    first_name="user1",
                    last_name="beta",
                    birthday="2019-09-05")
        user2 = User(email="*****@*****.**",
                     password=p2,
                     first_name="user2",
                     last_name="beta",
                     birthday="2019-09-05")
        circle = Circle("Cercle Beta 1")
        db.session.commit()
        UserToCircle(user=user, circle=circle, privilege="ADMIN")
        UserToCircle(user=user2, circle=circle)
        db.session.commit()
        device = db.session.query(Device).filter(
            Device.username == "device1").first()
        if device is None:
            device = Device(name="Device beta 1")
            device.circle = circle
            device.username = "******"
            device.set_password("test")
            device.activate(device.key)
            db.session.commit()
        if len(circle.conversations) == 0:
            conversation = Conversation(device_access=True,
                                        name="Conversation avec device",
                                        circle=circle)
            conversation2 = Conversation(device_access=False,
                                         name="Conversation sans device",
                                         circle=circle)
            db.session.commit()
            if len(user.conversation_links) == 0:
                cl1 = UserToConversation(privilege="ADMIN",
                                         user=user,
                                         conversation=conversation)
                cl2 = UserToConversation(user=user2, conversation=conversation)
                db.session.commit()
                Message(content="Message conversation avec device from user1",
                        link=cl1,
                        conversation=conversation)
                Message(content="Message conversation avec device from user2",
                        link=cl2,
                        conversation=conversation)
                message3 = Message(
                    content="Message conversation avec device from device",
                    is_user=False,
                    conversation=conversation)
                message3.device = device
                db.session.commit()
            if len(user2.conversation_links) == 0:
                cl3 = UserToConversation(privilege="ADMIN",
                                         user=user,
                                         conversation=conversation2)
                cl4 = UserToConversation(user=user2,
                                         conversation=conversation2)
                db.session.commit()
                Message(content="Message conversation sans device from user1",
                        link=cl3,
                        conversation=conversation2)
                Message(content="Message conversation sans device from user2",
                        link=cl4,
                        conversation=conversation2)
        db.session.commit()
예제 #26
0
파일: send.py 프로젝트: gothaur/Warsztat_2
                _to = User.get_user_by_name(connection_to_db,
                                            send_to).get_user_id()
                messages = Message.get_all_messages(connection_to_db,
                                                    user.get_user_id(),
                                                    receiver_id=_to)
                for i, m in enumerate(messages):
                    print(f"    Wiadomość {i + 1}: {m}")
            else:
                print(f'Wiadomości wysłane przez użytkownika: {username}')
                messages = Message.get_all_messages(connection_to_db,
                                                    user.get_user_id())
                for i, m in enumerate(messages):
                    print(f"    Wiadomość {i + 1}: {m}")

        if send_to or message:
            if message and send_to:
                _to = User.get_user_by_name(connection_to_db, send_to)
                if _to:
                    msg = Message(None, user.get_user_id(), _to.get_user_id(),
                                  message, 'now')
                    msg.save_to_db(connection_to_db)
                    print(f"Wiadomość: '{msg}' została wysłana")
                else:
                    print(f"Użytkownik {send_to} nie istnieje")
            elif list_of_messages:
                pass
            else:
                print("Podaj adresata oraz treść wiadomości")
    else:
        print("nieprawidłowy login lub hasło")
예제 #27
0
def first_message_to_user(content, email, circle_id, user):
    try:
        dest = db.session.query(UserModel).filter(
            UserModel.email == email).first()
        circle = db.session.query(Circle).filter(
            Circle.id == circle_id).first()
        if dest is None:
            raise e_message.TargetUserNotFound
        if circle is None:
            raise e_circle.CircleNotFound
        if not circle.has_member(user):
            raise e_circle.UserNotPartOfCircle
        if not circle.has_member(dest) and circle.has_member(user):
            raise e_circle.TargetUserNotPartOfCircle
        conversation = Conversation()
        conversation.circle = circle
        UserToConversation(privilege="ADMIN",
                           user=user,
                           conversation=conversation)
        UserToConversation(privilege="STANDARD",
                           user=dest,
                           conversation=conversation)
        message = Message(content=content["text_message"] if "text_message" in
                          content else "")
        message.conversation = conversation
        media_list = []
        if "files" in content:
            for file in content["files"]:
                media = Media()
                media.identifier = file
                MessageToMedia(message=message, media=media)
                db.session.commit()
                media_list.append(media.get_simple_content())
        db.session.commit()
        sockets.notify_user(dest, False, 'conversation', {
            "conversation_id": conversation.id,
            "event": 'invite'
        })
        message.conversation.mobile_notification(
            title="Conversation",
            body="Nouvelle conversation avec " + user.first_name)
        info_sender = "[" + conversation.name + "] " + user.first_name + " : "
        try:
            messenger_conversation_model_send(
                user.id, conversation, info_sender + message.text_content)
        except Exception:
            pass
        try:
            hangout_conversation_model_send(user.id, conversation,
                                            info_sender + message.text_content)
        except Exception:
            pass
        response = {
            "data": {
                "success": True,
                'media_list': media_list,
                'message_id': message.id,
                'conversation_id': message.conversation_id
            },
            "status_code": 200
        }
    except (e_message.MessageException, e_circle.CircleException) as exception:
        response = {
            "data": {
                "success": False,
                "message": exception.message
            },
            "status_code": exception.status_code
        }
    return response
예제 #28
0
def message_send(content, conversation_id, user, standalone=False):
    try:
        link = db.session.query(UserToConversation).filter(
            UserToConversation.conversation_id == conversation_id,
            UserToConversation.user_id == user.id).first()
        if link is None:
            raise e_conversation.ConversationNotFound
        message = Message(content=content["text_message"] if "text_message" in
                          content else "")
        message.conversation = link.conversation
        message.link = link
        media_list = []
        if "files" in content:
            for file in content["files"]:
                media = Media()
                media.identifier = file
                MessageToMedia(message=message, media=media)
                db.session.commit()
                media_list.append(media.get_simple_content())
        db.session.commit()
        if standalone is False:
            if not media_list:
                emit('message', {
                    'conversation_id': message.conversation_id,
                    'message': message.get_simple_json_compliant_content(),
                    'time': message.sent.isoformat(),
                    'sender': user.get_simple_json_compliant_content(),
                    'media_list': media_list,
                    'status': 'done'
                },
                     room='conversation_' + str(message.conversation_id),
                     namespace='/')
            else:
                emit('message', {
                    'conversation_id': message.conversation_id,
                    'message': message.get_simple_json_compliant_content(),
                    'status': 'pending'
                },
                     room='conversation_' + str(message.conversation_id),
                     namespace='/')
            message.conversation.mobile_notification(
                title="Message",
                body=user.first_name + " vous à envoyer un message.")
            conversation = db.session.query(Conversation).filter(
                link.conversation_id == Conversation.id).first()
            info_sender = "[" + link.conversation.name + "] " + user.first_name + " : "
            try:
                messenger_conversation_model_send(
                    link.user_id, conversation,
                    info_sender + message.text_content)
            except Exception:
                pass
            try:
                hangout_conversation_model_send(
                    link.user_id, conversation,
                    info_sender + message.text_content)
            except Exception:
                pass
        response = {
            "data": {
                "success": True,
                'media_list': media_list,
                'message_id': message.id
            },
            "status_code": 200
        }
    except e_conversation.ConversationException as exception:
        response = {
            "data": {
                "success": False,
                "message": exception.message
            },
            "status_code": exception.status_code
        }
    return response
from models.Message import Message

message1 = Message("0014", "0016", 1, 2, "hallo")
message3 = Message("0014", "0016", 1, 2, "hallo")
message2 = Message("0015", "0014", 1, 3, "hallo Welt")
message4 = Message("0015", "0014", 1, 3, "hallo Welt!")

print(message1)
print(message2)
print(message3)
print(message4)

print(message1 == message2)  #False
print(message1 == message3)  #True
print(message2 == message4)  #False
예제 #30
0
def message_send(conversation_id, content, socket):
    client = socket.get_client()
    conv = db.session.query(Conversation).filter(
        Conversation.id == conversation_id).first()
    if conv is None:
        raise Exception('Conversation introuvable')
    if socket.is_device:
        message = Message(content=content["text_message"]
                          if "text_message" in content else "",
                          is_user=False)
        message.conversation = conv
        message.device = client
        info_sender = "[" + conv.name + "] " + client.name + " : "
    else:
        link = db.session.query(UserToConversation). \
            filter(UserToConversation.user_id == socket.client_id,
                   UserToConversation.conversation_id == conv.id).first()
        if link is None:
            raise Exception("Vous ne faites pas partie de cette conversation")
        message = Message(content=content['text_message'] if 'text_message' in
                          content else '')
        message.conversation = conv
        message.link = link
        info_sender = "[" + conv.name + "] " + client.first_name + " : "
    db.session.commit()
    user = db.session.query(User).filter(socket.client_id == User.id).first()
    message.conversation.mobile_notification(title="Message",
                                             body=user.first_name +
                                             " vous à envoyer un message.")
    try:
        messenger_conversation_model_send(
            0 if socket.is_device else socket.client_id, conv,
            info_sender + content["text_message"])
    except Exception as e:
        logger.info("[%s] [%s] [%s] [%s] [%s] [%s]", "SOCKET", "", "message",
                    type(content), content, "FACEBOOK FAILED : " + str(e))
    try:
        hangout_conversation_model_send(
            0 if socket.is_device else socket.client_id, conv,
            info_sender + content["text_message"])
    except Exception as e:
        logger.info("[%s] [%s] [%s] [%s] [%s] [%s]", "SOCKET", "", "message",
                    type(content), content, "HANGOUT FAILED : " + str(e))
    media_list = []
    if 'files' in content:
        for file in content["files"]:
            media = Media()
            media.identifier = file
            media.message = message
            db.session.commit()
            media_list.append(media.get_json_compliant_content())
        socket.emit('media', {
            'media_list': media_list,
            'message_id': message.id
        })
    socket.emit('success', {'received': True, 'message_id': message.id})
    if not media_list:
        emit('message', {
            'conversation_id': conv.id,
            'message': message.get_simple_json_compliant_content(),
            'time': message.sent.isoformat(),
            'sender': client.get_simple_json_compliant_content(),
            'media_list': media_list,
            'status': 'done'
        },
             room='conversation_' + str(conv.id),
             namespace='/')
    else:
        emit('message', {
            'conversation_id': conv.id,
            'message': message.get_simple_json_compliant_content(),
            'status': 'pending'
        },
             room='conversation_' + str(conv.id),
             namespace='/')