예제 #1
0
def message(cursor, user, recipient, text):
    nm = Message()
    nm.from_id = user
    nm.to_id = recipient
    nm.text = text
    nm.creation_date = datetime.now()
    nm.save_to_db(cursor)
예제 #2
0
def send():
    form = SendForm(request.form)
    if request.method == 'POST' and form.validate():
        conn = get_connection()
        if conn:
            cursor = conn.cursor()
            sender_id = form.sender.data
            receiver_id = form.receiver.data
            sender = User.load_user_by_id(cursor, sender_id)

            if check_password(form.password.data, sender.hashed_password):
                message = Message()
                message.to_id = receiver_id
                message.from_id = sender_id
                message.text = form.message.data
                message.creation_date = datetime.today().strftime(
                    "%Y-%m-%d %H:%M:%S")
                message.save_to_db(cursor)
                conn.commit()
            else:
                flash("Błąd hasła!")
            cursor.close()
            conn.close()
            return redirect('/user/{}'.format(sender_id))
    return render_template('send_message.html', form=form)
예제 #3
0
def msg_operations():
    args = arg_parser()

    if args.username and args.password and args.send:
        user = check_user(args.username[0])
        user_to = check_user(args.to[0])
        if user and user_to:
            if checked(user.hashed_password):
                msg = Message()
                msg.from_id = user.id
                msg.to_id = user_to.id
                msg.text = args.send[0]
                msg.save_to_db(cursor)
            else:
                print("Błędne hasło!")
        else:
            print("Sprawdź dane username i username odbiorcy")

    if args.username and args.password and args.list:
        user = check_user(args.username[0])
        if user and checked(user.hashed_password):
            msg = Message.load_all_messages_for_user(cursor, user.id)
            msg_list = "Otrzymane komunikaty: \n Od | Treść | Utworzono \n"
            for row in msg:
                from_user = User.load_user_by_id(cursor, row.from_id)
                msg_list += " {} | {} | {} \n".format(from_user.username,
                                                      row.text,
                                                      row.creation_date)
            print(msg_list)
        else:
            print("Błędny username lub hasło")
예제 #4
0
    def send_message(self, adress: User, sender: User,
                     message_text: str) -> Message:
        """Create message to adress (User) to sender (User) into database."""

        connection = try_connect_db()
        cursor = get_cursor(connection)
        from_user = User()
        to_user = User()
        from_user = from_user.load_by_email(cursor, sender)
        to_user = to_user.load_by_email(cursor, adress)
        if not to_user:
            print("User {} does not exist. Message cannot be sent.".format(
                adress))
            cursor.close()
            connection.close()
            return False
        message = Message()
        message.from_id = from_user.id
        message.to_id = to_user.id
        message.text = message_text
        try:
            message.save(cursor)
        except Exception as err:
            print(
                'Data not saved to database due to the error:  {}'.format(err))
            cursor.close()
            connection.close()
            return False
        cursor.close()
        connection.close()
        return True
예제 #5
0
 def send_message(self, cursor, username, password, text, to_id) -> Message:
     user = self.login_user(cursor, username, password)
     if user:
         message = Message()
         message.from_id = user.id
         message.to_id = to_id
         message.text = text
         message.creation_date = datetime.now()
         message.save(cursor)
예제 #6
0
def create_message(from_id, to_id, tekst):
    cnx = connection()
    cursor = cnx.cursor()
    new_message = Message()
    new_message.from_id = from_id
    new_message.to_id = to_id
    new_message.tekst = tekst
    new_message.save_to_db(cursor)
    cnx.commit()
    print('dodano komunikat')
    cursor.close()
    cnx.close()
예제 #7
0
 def setUpClass(cls):
     cls.db = DB()
     cls.connection = cls.db.connect_db()
     cls.u_ids = []
     cls.msg_id = []
     cls.unames = []
     with cls.db.db_cursor(cls.connection) as curs:
         #create temporary users
         for i in range(5):
             u = User()
             u.username = '******' + ('').join(random.choices(ALPHABET, k=3))
             u.email = str(u.username) + '@email.com'
             u.hashed_password = {'password': ('').join(random.choices(ALPHABET, k=6)), 'salt': None}
             u.save_to_db(curs)
             cls.u_ids.append(u.load_user_by_username(curs, u.username).id)  #user ids
             cls.unames.append(u.username)
         cls.connection.commit()
         #create temporary messages
         for i in range(5):
             message = Message()
             message.from_id = random.choice(cls.u_ids)
             message.to_id = random.choice(cls.u_ids[1:])
             message.text = 'test message ' + ('').join(random.choices(ALPHABET, k=6))
             # print(cls.message.id)
             # self.message.date !
             save = message.save_to_db(curs)
             cls.connection.commit()
             cls.msg_id.append(message.id)  # append zmienia zmienna klasowa cls.msg_id = []
         # User 1 messages
         for i in range(5):
             message = Message()
             message.from_id = random.choice(cls.u_ids)
             message.to_id = cls.u_ids[0]
             message.text = 'test message ' + ('').join(random.choices(ALPHABET, k=6))
             # print(cls.message.id)
             # self.message.date !
             save = message.save_to_db(curs)
             cls.connection.commit()
             cls.msg_id.append(message.id)
         print(cls.msg_id)
예제 #8
0
 def send_message(username, password, to_id, text) -> Message:
     """Create message to adress (User) to sender (User) into database."""
     connection = create_connection()
     cursor = get_cursor(connection)
     user = User.get_by_username(cursor, username)
     if user and user.check_password(password):
         message = Message()
         message._id = -1
         message.from_id = user.id
         message.to_id = to_id
         message.tekst = text
         message.creation_date = datetime.now()
         message.save(cursor)
         cursor.close()
         connection.close()
     else:
         raise WrongParameterError("Wrong login or password!")
예제 #9
0
def send_message(_cursor, user, to_user, message_text):
    """
    Sends message using Message-class methods. Launched by main().

    :param _cursor: parameter passed with connector decorator
    :param user: User class object , passed by main()
    :param to_user: recipient user id, string type
    :param message_text: message text, string type
    :return: function prints success statement if message is sent
    """
    recipient = load_user(id=to_user)
    if not recipient:
        print('Recipient ID not found, please check and try again')
        return
    new_message = Message()
    new_message.to_id = recipient.id
    new_message.text = message_text
    new_message.from_id = user.id
    new_message.save_to_db(_cursor)
    print('Message sent!')
예제 #10
0
                User.load(id=message[2]).name, message[3],
                str(message[4])
            ]
            to_display.append(to_display_msg)

        print(to_display)
        # it might be necessary to check the dates and order by them

    elif args.list and (args.to or args.send):
        print("You used an incorrect set of arguments.")

    elif not args.list and args.to and args.send:

        to_user = User.load(name=args.to)
        if len(to_user) == 0:
            raise Exception(
                "The user you are trying to send the message to does not exist in the database."
            )

        message = Message()
        message.from_id = user._User__id
        message.to_id = to_user[0][0]
        message.text = args.send
        message.save()

    elif not args.list and not args.to and args.send:
        print("You did not specify the user you wish send the message to.")

    elif not args.list and args.to and not args.send:
        print("You did not write the message.")
예제 #11
0
if __name__ == '__main__':
    connection = get_connection()
    cursor = get_cursor(connection)

    if args.user and args.password:
        print(f"Podany login: {args.user}, podane hasło to: {args.password}")

        from_user = User.load_user_by_username(cursor, args.user)
        if check_password(args.password, from_user.hashed_password):
            print("Popawne hasło")
            if args.to:
                to_user = User.load_user_by_username(cursor, args.to)
                print('Adresat znajduje sie w bazie danych')
                if to_user and args.send:
                    message = Message()
                    message.from_id = from_user.id
                    message.to_id = to_user.id
                    message.text = args.send
                    message.creation_date = datetime.datetime.today()
                    message.save_to_db(cursor)
                    print(f'Wysłano wiadomość do użytkownika {args.to}')
                if not to_user:
                    print('Niepoprawny login adresata')
                if not args.send:
                    print('Komunikat musi zawierać treśc')

            elif args.list:
                loaded_user = User.load_user_by_username(cursor, args.user)
                messages = Message.load_all_messages_for_user(
                    cursor, loaded_user.id)
                print("ID: \t Od: \t Treść: \t Data:")
예제 #12
0
                    print(message.creation_date, message.from_id, message.text)
            else:
                raise Exception("Błąd użytkownika lub hasła.")
        else:
            raise Exception("Podaj login i hasło.")

    # Nadawanie komunikatu
    elif args.send:
        if args.username and args.password:
            if args.to:
                to_id = Message.get_user_id_by_username(cursor, args.to)
                if User.load_user_by_id(cursor, to_id):
                    from_id = Message.get_user_id_by_username(
                        cursor, args.username)
                    m = Message()
                    m.from_id = from_id
                    m.to_id = to_id
                    m.text = args.send
                    m.creation_date = datetime.now().strftime(
                        "%Y-%m-%d %H:%M:%S")
                    m.save_to_db(cursor)
                    conn.commit()
                    print("Wysłano komunikat.")
                else:
                    raise Exception("Nie ma takiego użytkownika!")
            else:
                raise Exception("Nie podano adresata!")
        else:
            raise Exception("Błąd użytkownika lub hasła!")
    else:
        raise Exception("Nie podano komunikatu!")
if args.list: # Listowanie wiadomości
    for message in user.load_all_messages():
        user_from = User.load_by_id(message.from_id)
        if user_from:
            print("AT {} USER {} wrote:".format(message.creation_date, user_from.username))
            print(message.text)
            print(message.id)
            print()
        else:
            # if user_from got deleted
            print("AT {} USER anonymous wrote:".format(message.creation_date))
            print(message.text)
            print(message.id)
            print()
elif args.delete: # Usuwanie wiadomości
    mesg = Message.load_by_id(args.delete)
    if mesg:
        if mesg.to_id == user.id:
            mesg.delete()
        else:
            print('Nie możesz usunąć tej wiadomości!')
    else:
        print('Nie znaleziono wiadomości o podanym ID')
else: # Wysyłka wiadomości - zachowanie domyślne
    target_user = User.load_by_username(args.to_user)
    if target_user:
        mesg = Message()
        mesg.from_id = user.id 
        mesg.to_id = target_user.id
        mesg.text = args.message
        mesg.save_to_db()
예제 #14
0
def save_message(message):
    print(message)
    if type(message.to_id) == PeerChannel:
        to_id = message.to_id.channel_id
    else:
        to_id = message.to_id
    message_item = session.query(Message).filter_by(message_id=message.id, to_id=to_id).first()

    if not message_item:
        new_message = Message()
        if message.id:
            new_message.message_id = message.id
        if message.action:
            new_message.message_type = 'action'
            if type(message.action) == MessageActionChatJoinedByLink:
                action = 'MessageActionChatJoinedByLink'
                new_message.inviter_id = message.action.inviter_id
                save_add_user(new_message.message_id, to_id, new_message.inviter_id, message.from_id, message.date,
                              'link')
                get_user_entity(new_message.inviter_id)
                new_message.action = action
            elif type(message.action) == MessageActionPinMessage:
                action = 'MessageActionPinMessage'
                new_message.action = action
            elif type(message.action) == MessageActionChatAddUser:
                action = 'MessageActionChatAddUser'
                new_message.action = action
                for user in message.action.users:
                    save_add_user(new_message.message_id, to_id, message.from_id, user, message.date, 'manually')
                    get_user_entity(user)
            elif type(message.action) == MessageActionChatDeleteUser:
                action = 'MessageActionChatDeleteUser'
                new_message.action = action

            elif type(message.action) == MessageActionChannelMigrateFrom:
                action = 'MessageActionChannelMigrateFrom'
                new_message.action = action
            else:
                print(message.action)
                print(message)
                raise (AssertionError("unknown action type" + type(message.action)))
        if to_id:
            new_message.to_id = to_id
        if message.date:
            new_message.date = message.date
        if message.message:
            new_message.message = message.message
        if message.out:
            new_message.out = message.out
        if message.mentioned:
            new_message.mentioned = message.mentioned
        if message.media_unread:
            new_message.media_unread = message.media_unread
        if message.silent:
            new_message.silent = message.silent
        if message.post:
            new_message.post = message.post
        if message.from_id:
            new_message.from_id = message.from_id
            get_user_entity(new_message.from_id)
        if 'fwd_from' in dir(message):
            if message.fwd_from:
                new_message.fwd_from = message.fwd_from.date
        if 'via_bot_id' in dir(message):
            if message.via_bot_id:
                new_message.via_bot_id = message.via_bot_id
        if 'reply_to_msg_id' in dir(message):
            if message.reply_to_msg_id:
                new_message.reply_to_msg_id = message.reply_to_msg_id
        if 'media' in dir(message):
            if message.media:
                # new_message.media = message.media
                new_message.message_type = 'media'
        if 'reply_markup' in dir(message):
            if message.reply_markup:
                new_message.reply_markup = message.reply_markup
        if 'edit_date' in dir(message):
            if message.edit_date:
                new_message.edit_date = message.edit_date
        if 'post_author' in dir(message):
            if message.post_author:
                new_message.post_author = message.post_author
        if 'grouped_id' in dir(message):
            if message.grouped_id:
                new_message.grouped_id = message.grouped_id
        session.add(new_message)
        session.commit()
예제 #15
0
            list_of_messages_to_user = Message.load_all_messages_for_user(
                cursor, u.id)
            for l in list_of_messages_to_user:
                print(l)
        else:
            print("Provided Username or password is incorrect")
    elif (args.username and args.password) and args.to and args.send:
        u = User.load_user_by_email(cursor, args.username)
        t = User.load_user_by_email(cursor, args.to)
        from_id = u.id
        to_id = t.id
        if check_password(args.password, u.hashed_password):
            if t:
                new = Message()
                new.to_id = to_id
                new.from_id = from_id
                new.text = args.send
                new.creation_date = datetime.datetime.now()
                new.save_to_db(cursor)
                cnx.commit()
            else:
                print("The reciepient does not exist ")
        else:
            print("Provided Username or password is incorrect")
    elif (args.username and args.password) and args.to and not args.send:
        print("The message has not been provided.")
    else:
        print(
            "Please type the following command to check all available options:\n python3 message_management.py --help"
        )
def solution(options):
    # -u -p -l parameters (List all messages for this user)
    if options.username and options.password and options.list and not options.send and not options.to:

        # Check login and pass
        user_collection = []
        try:
            user_collection = User.load_all_ids_usernames(cnx_cursor[1])
        except:
            print("Failed to load user data.")

        # Check login
        for item in user_collection:
            if options.username == item.username:

                # Load one user
                user_data = User.load_user_by_id(cnx_cursor[1], item.id)

                # Check if password is correct
                if models.hasher.check_password(
                        options.password, user_data.hashed_password) is False:
                    return "Wrong password."

                # Collect all messages
                message_collection = Message.load_all_messages_for_user(
                    cnx_cursor[1], item.id)

                # Display
                print("### Messages for you:")
                for element in message_collection:
                    print("From:", element.from_user, "\nDate:",
                          element.creation_date, "\nMessage:",
                          element.message_content, "\n")
                return "###"

        return "No such user found."

    # -u -p -s -t parameters (Send message to specified user)
    elif options.username and options.password and options.send and not options.list:

        user_collection = []
        try:
            user_collection = User.load_all_ids_usernames(cnx_cursor[1])
        except:
            print("Failed to load user data.")

        # Check login
        for item in user_collection:
            if options.username == item.username:

                # Load one user
                user_data = User.load_user_by_id(cnx_cursor[1], item.id)

                # Check if password is correct
                if models.hasher.check_password(
                        options.password, user_data.hashed_password) is False:
                    return "Wrong password."

                # See if options.to is provided; if not, display no recipient. Likely to be redundant since parameters
                # are checked by the parser.
                if options.to is False:
                    return "No recipient provided in argument -t"

                # See if recipient is in database
                for member in user_collection:
                    if options.to == member.username:
                        recipient_id = member.id

                        # Check message length <= 255
                        if len(options.send) > 255:
                            return "Message too long. Maximum is 255 characters."

                        if len(options.send) < 1:
                            return "Nothing to send. Please type message after parameter -s"

                        # Send message
                        new_mssg = Message()
                        new_mssg.from_id = item.id
                        new_mssg.to_id = recipient_id
                        new_mssg.message_content = options.send
                        new_mssg.creation_date = datetime.datetime.fromtimestamp(
                            time.time()).strftime('%Y-%m-%d %H:%M:%S')
                        new_mssg.save_to_db(cnx_cursor[1])
                        return "Message sent."
                return "No recipient found in database."

        return "No such user found."

    else:
        return "No function for those parameters found. Try -u -p -s -t for sending or -u -p -l for listing messages."