Beispiel #1
0
def create_message(from_username, to_username, text, media_url=None):
    """
           This function create a message in the database.


           *Parameter:*

               - *from_username*: user who is send the message .
               - *to_username*: user who is received the message.
               - *text*: body of text.
               - *media_url*: url of the media.

           *Returns:*

               - *None*: if the query was executed successfully.
               - *Exception object*: if there is something wrong, return right exception.
      """
    if actions.is_user(from_username) is False:
        raise Exception('Username who sent this message does not exist.')
    if actions.is_user(to_username) is False:
        raise Exception(
            'Username who want to receive this message does not exist.')
    return query_factory.create_message(from_username, to_username,
                                        datetime.datetime.now(), text,
                                        media_url)
Beispiel #2
0
def get_recent_conversationers(from_username,
                               last_conversationers_retrieved_username=None):
    """
         This function get list of conversationers between two users converting lists of dictionaries
         into lists of Conversation model, it calls function from query factory that returns lists of
         dictionaries fit Conversation model with the given pagination.

         *Parameter:*

             - *from_username*: user who is send the message.
             - *last_conversationers_retrieved_username*: id of last message retrieved

         *Returns:*

             - *models.User object*
    """
    if actions.is_user(from_username) is False:
        raise Exception('Username who sent this message does not exist.')
    if last_conversationers_retrieved_username is not None:
        if actions.is_user(last_conversationers_retrieved_username) is False:
            raise Exception('Username does not exist.')
    conversationers = query_factory.get_recent_conversationers(from_username)
    try:
        conversationers = actions.paginate(
            dictionaries_list=conversationers,
            required_size=20,
            start_after_key='username',
            start_after_value=last_conversationers_retrieved_username)
    except TypeError:
        raise
    if conversationers is None:
        return []
    conversationer_list = []
    if len(conversationers) == 0:
        return conversationer_list
    for conversation in conversationers:
        to_username = conversation['username']

        dictionary = {'username': to_username}
        temp = {'screen_name': conversation['screen_name']}
        dictionary.update(temp)
        temp = {'profile_image_url': conversation['profile_image_url']}
        dictionary.update(temp)
        flag = check_follow(from_username, to_username)
        temp = {'following': flag}
        dictionary.update(temp)
        flag = check_follow(to_username, from_username)
        temp = {'follows_you': flag}
        dictionary.update(temp)
        flag = check_block(from_username, to_username)
        temp = {'blocked': flag}
        dictionary.update(temp)
        flag = check_mute(from_username, to_username)
        temp = {'muted': flag}
        dictionary.update(temp)
        user = User(dictionary)

        conversationer_list.append(user)
    return conversationer_list
Beispiel #3
0
def create_notifications(involved_username,
                         notified_username,
                         type_notification,
                         kweek_id=None):
    """
     This function create a notification in the database.


     *Parameter:*
         - *notified_username* :user who is notified from the notification
         - *involved_username*: user who is responsible for the notification.
         - *type_notification*: type of the notification [FOLLOW-REKWEEK-LIKE-REPLY-MENTION].
         - *kweek_id*: the id of the kweek involved.

     *Returns:*

         - *None*: If the query was executed successfully.
         - *Exception* object: If the query produced an error.
     """
    if involved_username == notified_username:
        return None
    if kweek_id is not None and is_kweek(kweek_id) is False:
        raise Exception('A kweek with this id does not exist')
    if actions.is_user(involved_username) is False:
        raise Exception('Involved_username does not exist')
    if actions.is_user(notified_username) is False:
        raise Exception('Notified_username does not exist')
    if is_notification(involved_username, notified_username, type_notification,
                       kweek_id) is True:
        return "already exists"
    response = query_factory.create_notifications(involved_username,
                                                  notified_username,
                                                  type_notification, kweek_id,
                                                  datetime.datetime.now(),
                                                  False)
    if type_notification == "REKWEEK":
        result = involved_username + " rekweeked your kweek."
    elif type_notification == "LIKE":
        result = involved_username + " liked your kweek."
    elif type_notification == "FOLLOW":
        result = involved_username + " followed you."
    elif type_notification == "REPLY":
        result = involved_username + " replied to your kweek"
    else:
        result = involved_username + " mentioned you."
    channel = notified_username
    socketio.emit(channel, result)
    return response
Beispiel #4
0
def create_profile(username, screen_name, birth_date):
    """
                The function creates new profile in database.

                *Parameters*:
                    - *username (string)*: The username .
                    - *screen_name*: screen_name.
                    -*birth_date*: date of birth.
                *Returns*:
                    - *True*: profile created successfully.
                    - *False*: if profile is already created or database error .
    """
    if username is None or username == "":
        return False
    check_user = actions.is_user(username)
    if not check_user:
        return False
    time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    response = query_factory.create_profile(
        username,
        screen_name,
        birth_date,
        time,
        profile_image_url=create_url('picture', 'profile.jpg'),
        banner_url=create_url('banner', 'banner.jpg'))
    if response is None:
        return True
    return False
Beispiel #5
0
    def get(self, authorized_username):
        """ Retrieve a list of users that are followed by the username. """

        if 'username' not in request.args.keys():
            abort(404, message='No username was sent.')
        else:
            username = request.args.get('username')
            last_retrieved_username = request.args.get(
                'last_retrieved_username')
            if not trends_actions.is_user(username):
                abort(404, message='A user with this username does not exist.')
            try:
                following_list = actions.get_profile_following(
                    username=username,
                    last_retrieved_username=last_retrieved_username,
                    authorized_username=authorized_username)
                if following_list is None:
                    abort(
                        404,
                        message=
                        'A user with the provided last_retrieved_username does not exist.'
                    )
                return following_list, 200
            except TypeError:
                abort(500, message='An error occurred in the server.')
            except ValueError:
                abort(400, 'Invalid username provided.')
Beispiel #6
0
def get_user_profile(authorized_username, username):
    """
            The function return user profile for a specific user.

            *Parameters*:
                - *authorized_username (string)*: The user that is logged in now.
                - *username (string)*: The user that we will test friendship on it like (following ..)

            *Returns*:
                - *UserProfile*: an object of user profile .
    """
    if username is None:
        return -1
    check_user = actions.is_user(username)
    if not check_user:
        return -1
    profile = query_factory.get_user_profile(username)

    profile["profile_image_url"] = create_url('picture',
                                              profile["profile_image_url"])
    profile["profile_banner_url"] = create_url('banner',
                                               profile["profile_banner_url"])
    profile["followers_count"] = query_factory.get_user_followers(
        username)["count"]
    profile["following_count"] = query_factory.get_user_following(
        username)["count"]
    profile["kweeks_count"] = query_factory.get_number_of_kweeks(
        username)['count']
    profile["likes_count"] = query_factory.get_number_of_likes(
        username)['count']
    friendship = actions.get_friendship(authorized_username, username)
    profile.update(friendship)
    return UserProfile(profile)
Beispiel #7
0
def get_messages(from_username, to_username, last_message_retrieved_id=None):
    """
         This function get list of messages from (from_user)to (to_username) converting lists of dictionaries
         into lists of DirectMessage model, it calls function from query factory that returns lists of
         dictionaries fit DirectMessage model with the given pagination.

         *Parameter:*

             - *from_username*: user who is send the message.
             - *to_username*: user who is received the message.
             - *last_message_retrieved_id*: id of last message retrieved

         *Returns:*

             - *models.Notification object*
    """

    if last_message_retrieved_id is not None:
        try:
            last_message_retrieved_id = int(last_message_retrieved_id)
        except ValueError:
            raise
    if actions.is_user(from_username) is False:
        raise Exception('Username who sent this message does not exist.')
    if actions.is_user(to_username) is False:
        raise Exception(
            'Username who want to receive this message does not exist.')
    messages = query_factory.get_messages(from_username, to_username)
    try:
        messages = actions.paginate(
            dictionaries_list=messages,
            required_size=20,
            start_after_key='id',
            start_after_value=last_message_retrieved_id)
    except TypeError:
        raise
    if messages is None:
        return None
    message_list = []
    if len(messages) == 0:
        return message_list
    for message in messages:
        message['created_at'] = change_time(message['created_at'])
        message_list.append(DirectMessage(message))
    return message_list
Beispiel #8
0
def create_notifications(involved_username,
                         notified_username,
                         type_notification,
                         kweek_id=None):
    """
     This function create a notification in the database.


     *Parameter:*

         - *involved_username*: user who is responsible for the notification.
         - *type_notification*: type of the notification [FOLLOW-REKWEEK-LIKE].
         - *kweek_id*: the id of the kweek involved.

     *Returns:*

         - *None*: If the query was executed successfully.
         - *Exception* object: If the query produced an error.
     """
    if kweek_id is not None and is_kweek(kweek_id) is False:
        raise Exception('A kweek with this username does not exist')
    if actions.is_user(involved_username) is False:
        raise Exception('Involved_username does not exist')
    if actions.is_user(notified_username) is False:
        raise Exception('Notified_username does not exist')
    if type_notification == 'REPLY' or type_notification == 'MENTION':
        return query_factory.create_notifications(involved_username,
                                                  notified_username,
                                                  type_notification, kweek_id,
                                                  datetime.datetime.now(),
                                                  True)
    if type_notification != 'FOLLOW' and type_notification != 'REKWEEK' and type_notification != 'LIKE':
        raise Exception('Type does not exist')
    if is_notification(involved_username, notified_username, type_notification,
                       kweek_id) is True:
        return "already exists"
    return query_factory.create_notifications(involved_username,
                                              notified_username,
                                              type_notification, kweek_id,
                                              datetime.datetime.now(), False)
Beispiel #9
0
 def post(self, authorized_username):
     """ Block a certain user using his username. """
     data = request.get_json()
     username = data.get('username')
     if not trends_actions.is_user(username):
         abort(404, message='A user with this username does not exist.')
     if username == authorized_username:
         abort(400, message='A bad request can not block your self.')
     response = actions.block(authorized_username=authorized_username,
                              username=username)
     if response is None:
         return "user is blocked successfully", 200
     return response, 400
Beispiel #10
0
 def post(self, authorized_username):
     """ Follow a certain user using their username. """
     data = request.get_json()
     username = data.get('username')
     if not trends_actions.is_user(username):
         abort(404, message='A user with this username does not exist.')
     if username == authorized_username:
         abort(400, message='A bad request can not follow your self')
     response = actions.follow(username=username,
                               authorized_username=authorized_username)
     if response is None:
         return 'User followed successfully', 200
     return response, 400
Beispiel #11
0
def create_message(from_username, to_username, text, media_id=None):
    """
           This function create a message in the database.


           *Parameter:*

               - *from_username*: user who is send the message .
               - *to_username*: user who is received the message.
               - *text*: body of text.
               - *media_id*: url of the media.

           *Returns:*

               - *None*: if the query was executed successfully.
               - *Exception object*: if there is something wrong, return right exception.
      """

    if actions.is_user(from_username) is False:
        raise Exception('Username who sent this message does not exist.')
    if actions.is_user(to_username) is False:
        raise Exception(
            'Username who want to receive this message does not exist.')
    media_id = media_actions.create_url(media_id)
    if text is None and media_id is None:
        raise Exception(
            'message is empty or media_id is invalid and there is not text')
    media_url = media_id
    response = query_factory.create_message(from_username, to_username,
                                            datetime.datetime.now(), text,
                                            media_url)
    message = query_factory.get_messages(from_username, to_username)[0]
    if from_username < to_username:
        channel = from_username + to_username
    else:
        channel = to_username + from_username
    socketio.emit(channel, marshal(message, DirectMessage.api_model))
    return response
Beispiel #12
0
 def delete(self, authorized_username):
     """ Unmute a certain user using his username. """
     if 'username' not in request.args.keys():
         abort(404, message='No username was sent.')
     username = request.args.get('username')
     if not trends_actions.is_user(username):
         abort(404, message='A user with this username does not exist.')
     if username == authorized_username:
         abort(400, message='A bad request can not unmute your self.')
     response = actions.unmute(authorized_username=authorized_username,
                               username=username)
     if response is None:
         return "user is unmuted successfully", 200
     return response, 400
Beispiel #13
0
 def post(self, authorized_username):
     """ Retrieves a list of recent users done using search. """
     data = request.get_json()
     last_conversationers_retrieved_username = request.args.get(
         'last_conversationers_retrieved_username')
     if tre_time_actions.is_user(last_conversationers_retrieved_username)is False \
             and last_conversationers_retrieved_username is not None:
         abort(404, message='Username does not exist.')
     search_user = data["search_user"]
     try:
         conversationers = user_profile_actions.search_user(
             authorized_username, search_user,
             last_conversationers_retrieved_username)
         if len(conversationers) == 0:
             return [], 200
         return conversationers, 200
     except TypeError:
         abort(500, message='An error occurred in the server.')
Beispiel #14
0
def get_user_profile(authorized_username, username):
    """
            The function return user profile for a specific user.

            *Parameters*:
                - *authorized_username (string)*: The user that is logged in now.
                - *username (string)*: The user that we will test friendship on it like (following ..)

            *Returns*:
                - *UserProfile*: an object of user profile .
    """
    if username is None:
        return -1
    check_user = actions.is_user(username)
    if not check_user:
        return -1
    profile = query_factory.get_user_profile(username)
    check_block = user_interaction_query_factory.if_blocked(
        username, authorized_username)['count']
    if check_block == 1:
        dict_blocked = {
            'username': profile['username'],
            'screen_name': profile['screen_name'],
            'profile_image_url': profile['profile_image_url'],
            'profile_banner_url': profile['profile_banner_url']
        }
        return dict_blocked
    profile["followers_count"] = query_factory.get_user_followers(
        username)["count"]
    profile["following_count"] = query_factory.get_user_following(
        username)["count"]
    profile["kweeks_count"] = query_factory.get_number_of_kweeks(
        username)['count']
    profile["likes_count"] = query_factory.get_number_of_likes(
        username)['count']
    friendship = actions.get_friendship(authorized_username, username)
    profile.update(friendship)
    return UserProfile(profile)
Beispiel #15
0
def get_conversations(auth_username, last_conversations_retrieved_id=None):
    """
         This function get list of conversation between two users converting lists of dictionaries
         into lists of Conversation model, it calls function from query factory that returns lists of
         dictionaries fit Conversation model with the given pagination.

         *Parameter:*

             - *auth_username*: user who is logging in.
             - *last_conversations_retrieved_id*: id of last message retrieved

         *Returns:*

             - *models.Conversation object*
    """

    if last_conversations_retrieved_id is not None:
        try:
            last_conversations_retrieved_id = int(
                last_conversations_retrieved_id)
        except ValueError:
            raise
    if actions.is_user(auth_username) is False:
        raise Exception('Username who sent this message does not exist.')
    conversations = query_factory.get_conversations(auth_username)
    try:
        conversations = actions.paginate(
            dictionaries_list=conversations,
            required_size=20,
            start_after_key='id',
            start_after_value=last_conversations_retrieved_id)
    except TypeError:
        raise
    if conversations is None:
        return None

    conversation_list = []
    if len(conversations) == 0:
        return conversation_list
    for conversation in conversations:
        to_username = conversation['to_username']
        from_username = conversation['from_username']
        dictionary = {'id': conversation['id']}
        temp = {'from_username': from_username}
        dictionary.update(temp)
        temp = {'to_username': to_username}
        dictionary.update(temp)
        new_format = change_time(conversation['created_at'])
        temp = {'created_at': new_format}
        dictionary.update(temp)
        temp = {'text': conversation['text']}
        dictionary.update(temp)
        temp = {'media_url': conversation['media_url']}
        dictionary.update(temp)
        direct_message = DirectMessage(dictionary)
        dic = {'last_message': direct_message}
        if to_username == auth_username:
            username = from_username
        else:
            username = to_username
        dictionary = {'username': username}
        temp = {'screen_name': conversation['screen_name']}
        dictionary.update(temp)
        temp = {'profile_image_url': conversation['profile_image_url']}
        dictionary.update(temp)
        flag = check_follow(auth_username, username)
        temp = {'following': flag}
        dictionary.update(temp)
        flag = check_follow(username, auth_username)
        temp = {'follows_you': flag}
        dictionary.update(temp)
        flag = check_block(auth_username, username)
        temp = {'blocked': flag}
        dictionary.update(temp)
        flag = check_mute(auth_username, username)
        temp = {'muted': flag}
        dictionary.update(temp)
        user = User(dictionary)
        dic2 = {'user': user}
        dic2.update(dic)
        conversation_list.append(Conversation(dic2).to_json())
    return conversation_list