Ejemplo n.º 1
0
def handle_new_chat(user=None):
    try:
        if user in {None, ""}:
            raise TypeError("User not provided.")

        s = Session()
        sender = s.query(User).filter(User.username == current_user.user).first()
        recipient = s.query(User).filter(User.username == user).first()

        if not recipient:
            raise ValueError("User doesn't exist")

        # Check if chats already exists (client should do this but just an extra check)
        existingChat = (
            s.query(Chat)
            .filter(Chat.users.contains(sender), Chat.users.contains(recipient))
            .first()
        )
        if existingChat:
            raise ValueError("Chat already exists")

        chat = Chat()
        sender.chats.append(chat)
        recipient.chats.append(chat)
        s.commit()

        join_room(chat.id)
        socket.emit(
            "ADD_CHAT",
            {
                "id": chat.id,
                "recipient": recipient.username,
                "recipientId": recipient.id,
                "avatar": recipient.avatar,
            },
            room=request.sid,
        )

        recipient_sid = socket_session.get(recipient.id)

        if recipient_sid:
            join_room(chat.id, sid=recipient_sid.decode("utf-8"))
            socket.emit(
                "ADD_CHAT",
                {
                    "id": chat.id,
                    "recipient": current_user.user,
                    "recipientId": sender.id,
                    "avatar": sender.avatar,
                    "last_message": "",
                    "last_message_timestamp": "",
                },
                room=recipient_sid.decode("utf-8"),
            )
    except (ValueError, TypeError) as err:
        print(err)
        genError(request.sid, err)
    finally:
        if "s" in locals():
            s.close()
Ejemplo n.º 2
0
def getChats(sid, s):
    try:
        if sid in {None, ""}:
            raise ValueError("SID and/or session not provided!")
        query = s.query(User).get(current_user.user_id).chats.all()
        chats = [
            {
                "id": i.id,
                "recipient": i.users.filter(User.id != current_user.user_id)
                .first()
                .username,
                "recipientId": i.users.filter(User.id != current_user.user_id)
                .first()
                .id,
                "active": socket_session.get(
                    i.users.filter(User.id != current_user.user_id).first().id
                )
                != None,
                "avatar": i.users.filter(User.id != current_user.user_id)
                .first()
                .avatar,
                "last_message": i.last_message,
                "last_message_timestamp": str(i.last_message_timestamp),
            }
            for i in query
        ]

        for i in chats:
            join_room(i["id"])
        socket.emit("LOAD_CHATS", chats, room=sid) 

    except ValueError as err:
        print(err)
        genError(request.sid, err)
Ejemplo n.º 3
0
def login_status(status, id, s):
    try:
        friends = s.query(User).get(id).friends
        for i in friends:
            friend_sid = socket_session.get(i.id)
            if friend_sid:
                socket.emit(status, id, room=friend_sid.decode("utf-8"))
    except (ValueError, TypeError) as err:
        print(err)
Ejemplo n.º 4
0
def handleFriendRequest(id=None):
    print("AVATAR: ", current_user.avatar)
    try:
        if None or "" in {id}:
            raise ValueError("Id and/or Username not provided!")

        s = Session()
        recipient = s.query(User).get(id)

        if not recipient:
            raise ValueError("Recipient not found!")

        # Check they are not already friends
        if recipient.friends.filter(User.id == current_user.user_id).first():
            return False

        # Check a request has not already been sent and no
        # action has been taken by the user
        existingNotification = recipient.notifications.filter(
            Notification.sender == current_user.user,
            Notification.type == "FRIEND_REQUEST",
        ).first()

        if existingNotification:
            return False

        n = Notification(
            "FRIEND_REQUEST",
            current_user.user,
            f"{current_user.user} sent you a friend request",
            current_user.avatar,
        )
        recipient.notifications.append(n)
        s.commit()

        recipient_sid = socket_session.get(id)
        if recipient_sid:
            socket.emit(
                "ADD_NOTIFICATION",
                {
                    "id": n.id,
                    "type": n.type,
                    "dismissed": n.dismissed,
                    "sender": current_user.user,
                    "message": n.message,
                    "avatar": current_user.avatar,
                },
                room=recipient_sid.decode("utf-8"),
            )
    except ValueError as err:
        print(err)
        genError(request.sid, err)
    finally:
        if "s" in locals():
            s.close()
Ejemplo n.º 5
0
def handle_logout():
    try:
        sid = socket_session.get(current_user.user_id).decode("utf-8")
        s = Session()
        login_status("SET_FRIEND_OFFLINE", current_user.user_id, s)
        if sid:
            socket.emit("LOGOUT", room=sid)
            logon_session.delete(current_user.session)
            socket_session.delete(current_user.user_id)
            disconnect(sid=sid, namespace="/")
            logout_user()
        return make_response("Logged out", 200)
    except Exception as err:
        print(err)
    finally:
        if "s" in locals():
            s.close()
Ejemplo n.º 6
0
def getFriends(sid, s):
    try:
        if sid in {None, ""}:
            raise TypeError("SID and/or session not provided!")
        friends = s.query(User).get(current_user.user_id).friends
        socket.emit(
            "LOAD_FRIENDS",
            [
                {
                    "id": i.id,
                    "username": i.username,
                    "avatar": i.avatar,
                    "active": socket_session.get(i.id) != None,
                }
                for i in friends
            ],
            room=sid,
        )
    except TypeError as err:
        print(err)
        genError(request.sid, err)
Ejemplo n.º 7
0
def handle_friend_request_accepted(data=None):
    try:
        if None or "" in {data.get("username"), data.get("id")}:
            raise TypeError("Id and/or Username not provided.")

        s = Session()

        # Get sender from DB
        sender = s.query(User).filter(User.username == data["username"]).first()

        if not sender:
            raise ValueError("Sender not found!")

        # Get recipient from DB
        recipient = s.query(User).get(current_user.user_id)

        if not recipient:
            raise ValueError("Recipient not found!")

        # Create friendship
        sender.add_friend(recipient)
        recipient.add_friend(sender)

        # Delete request notification and emit change to client
        notification = s.query(Notification).get(data["id"])
        s.delete(notification)
        socket.emit("DELETE_NOTIFICATION", data["id"], room=request.sid)

        # Create Notification for request acceptance.
        n = Notification(
            "FRIEND_REQUEST_ACCEPTED",
            current_user.user,
            f"{recipient.username} accepted your friend request.",
            current_user.avatar,
        )
        sender.notifications.append(n)
        s.commit()

        # Send friend details to recipient (request.sid),. the user that accepted the request.
        socket.emit(
            "ADD_FRIEND",
            {
                "id": sender.id,
                "username": sender.username,
                "active": False,
                "avatar": sender.avatar,
            },
            room=request.sid,
        )

        # Check if user that sent friend request is currently online
        senderSession = socket_session.get(sender.id)
        if senderSession:
            socket.emit(
                "ADD_NOTIFICATION",
                {
                    "type": n.type,
                    "sender": recipient.username,
                    "message": n.message,
                    "dismissed": n.dismissed,
                    "avatar": n.avatar,
                },
                room=senderSession.decode("utf-8"),
            )
            socket.emit(
                "ADD_FRIEND",
                {"id": recipient.id, "username": recipient.username, "active": True},
                room=senderSession.decode("utf-8"),
            )

    except (ValueError, TypeError) as err:
        print(err)
        genError(request.sid, err)
    finally:
        if "s" in locals():
            s.close()