Ejemplo n.º 1
0
    def CreateGroupChat(self, request, context):
        with session_scope() as session:
            recipient_user_ids = [
                user_id
                for user_id in (
                    session.execute(
                        select(User.id).where_users_visible(context).where(User.id.in_(request.recipient_user_ids))
                    )
                    .scalars()
                    .all()
                )
            ]

            # make sure all requested users are visible
            if len(recipient_user_ids) != len(request.recipient_user_ids):
                context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.USER_NOT_FOUND)

            if not recipient_user_ids:
                context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.NO_RECIPIENTS)

            if len(recipient_user_ids) != len(set(recipient_user_ids)):
                # make sure there's no duplicate users
                context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.INVALID_RECIPIENTS)

            if context.user_id in recipient_user_ids:
                context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.CANT_ADD_SELF)

            if len(recipient_user_ids) == 1:
                # can only have one DM at a time between any two users
                other_user_id = recipient_user_ids[0]

                # the following sql statement selects subscriptions that are DMs and have the same group_chat_id, and have
                # user_id either this user or the recipient user. If you find two subscriptions to the same DM group
                # chat, you know they already have a shared group chat
                count = func.count(GroupChatSubscription.id).label("count")
                if session.execute(
                    select(count)
                    .where(
                        or_(
                            GroupChatSubscription.user_id == context.user_id,
                            GroupChatSubscription.user_id == other_user_id,
                        )
                    )
                    .where(GroupChatSubscription.left == None)
                    .join(GroupChat, GroupChat.conversation_id == GroupChatSubscription.group_chat_id)
                    .where(GroupChat.is_dm == True)
                    .group_by(GroupChatSubscription.group_chat_id)
                    .having(count == 2)
                ).scalar_one_or_none():
                    context.abort(
                        grpc.StatusCode.FAILED_PRECONDITION, "You already have a direct message chat with this user."
                    )

            conversation = Conversation()
            session.add(conversation)

            group_chat = GroupChat(
                conversation=conversation,
                title=request.title.value,
                creator_id=context.user_id,
                is_dm=True if len(recipient_user_ids) == 1 else False,  # TODO
            )
            session.add(group_chat)

            your_subscription = GroupChatSubscription(
                user_id=context.user_id,
                group_chat=group_chat,
                role=GroupChatRole.admin,
            )
            session.add(your_subscription)

            for recipient_id in request.recipient_user_ids:
                subscription = GroupChatSubscription(
                    user_id=recipient_id,
                    group_chat=group_chat,
                    role=GroupChatRole.participant,
                )
                session.add(subscription)

            _add_message_to_subscription(session, your_subscription, message_type=MessageType.chat_created)

            session.flush()

            return conversations_pb2.GroupChat(
                group_chat_id=group_chat.conversation_id,
                title=group_chat.title,
                member_user_ids=_get_visible_members_for_subscription(your_subscription),
                admin_user_ids=_get_visible_admins_for_subscription(your_subscription),
                only_admins_invite=group_chat.only_admins_invite,
                is_dm=group_chat.is_dm,
                created=Timestamp_from_datetime(group_chat.conversation.created),
                mute_info=_mute_info(your_subscription),
            )
Ejemplo n.º 2
0
def add_dummy_users():
    try:
        logger.info(f"Adding dummy users")
        with session_scope() as session:
            with open("src/data/dummy_users.json", "r") as file:
                data = json.loads(file.read())

            for user in data["users"]:
                new_user = User(
                    username=user["username"],
                    email=user["email"],
                    hashed_password=hash_password(user["password"])
                    if user["password"] else None,
                    name=user["name"],
                    city=user["location"]["city"],
                    geom=create_coordinate(user["location"]["lat"],
                                           user["location"]["lng"]),
                    geom_radius=user["location"]["radius"],
                    verification=user["verification"],
                    community_standing=user["community_standing"],
                    birthdate=date(year=user["birthdate"]["year"],
                                   month=user["birthdate"]["month"],
                                   day=user["birthdate"]["day"]),
                    gender=user["gender"],
                    languages="|".join(user["languages"]),
                    occupation=user["occupation"],
                    about_me=user["about_me"],
                    about_place=user["about_place"],
                    countries_visited="|".join(user["countries_visited"]),
                    countries_lived="|".join(user["countries_lived"]),
                    hosting_status=hostingstatus2sql[HostingStatus.Value(
                        user["hosting_status"])]
                    if "hosting_status" in user else None,
                )
                session.add(new_user)

            session.commit()

            for username1, username2 in data["friendships"]:
                friend_relationship = FriendRelationship(
                    from_user_id=get_user_by_field(session, username1).id,
                    to_user_id=get_user_by_field(session, username2).id,
                    status=FriendStatus.accepted,
                )
                session.add(friend_relationship)

            session.commit()

            for reference in data["references"]:
                reference_type = (ReferenceType.HOSTED
                                  if reference["type"] == "hosted" else
                                  (ReferenceType.SURFED if reference["type"]
                                   == "surfed" else ReferenceType.FRIEND))
                new_reference = Reference(
                    from_user_id=get_user_by_field(session,
                                                   reference["from"]).id,
                    to_user_id=get_user_by_field(session, reference["to"]).id,
                    reference_type=reference_type,
                    text=reference["text"],
                    rating=reference["rating"],
                    was_safe=reference["was_safe"],
                )
                session.add(new_reference)

            session.commit()

            for group_chat in data["group_chats"]:
                # Create the chat
                creator = group_chat["creator"]

                conversation = Conversation()
                session.add(conversation)

                chat = GroupChat(
                    conversation=conversation,
                    title=group_chat["title"],
                    creator_id=get_user_by_field(session, creator).id,
                    is_dm=group_chat["is_dm"],
                )
                session.add(chat)

                for participant in group_chat["participants"]:
                    subscription = GroupChatSubscription(
                        user_id=get_user_by_field(session,
                                                  participant["username"]).id,
                        group_chat=chat,
                        role=GroupChatRole.admin if participant["username"]
                        == creator else GroupChatRole.participant,
                        joined=parser.isoparse(participant["joined"]),
                    )
                    session.add(subscription)

                for message in group_chat["messages"]:
                    session.add(
                        Message(
                            message_type=MessageType.text,
                            conversation=chat.conversation,
                            author_id=get_user_by_field(
                                session, message["author"]).id,
                            time=parser.isoparse(message["time"]),
                            text=message["message"],
                        ))

            session.commit()

    except IntegrityError:
        logger.error("Failed to insert dummy users, is it already inserted?")
Ejemplo n.º 3
0
    def CreateGroupChat(self, request, context):
        if len(request.recipient_user_ids) < 1:
            context.abort(grpc.StatusCode.INVALID_ARGUMENT,
                          errors.NO_RECIPIENTS)

        if len(request.recipient_user_ids) != len(
                set(request.recipient_user_ids)):
            # make sure there's no duplicate users
            context.abort(grpc.StatusCode.INVALID_ARGUMENT,
                          errors.INVALID_RECIPIENTS)

        if context.user_id in request.recipient_user_ids:
            context.abort(grpc.StatusCode.INVALID_ARGUMENT,
                          errors.CANT_ADD_SELF)

        with session_scope(self._Session) as session:
            if len(request.recipient_user_ids) == 1:
                # can only have one DM at a time between any two users
                other_user_id = request.recipient_user_ids[0]

                # the following query selects subscriptions that are DMs and have the same group_chat_id, and have
                # user_id either this user or the recipient user. If you find two subscriptions to the same DM group
                # chat, you know they already have a shared group chat
                count = func.count(GroupChatSubscription.id).label("count")
                if (session.query(count).filter(
                        or_(
                            GroupChatSubscription.user_id == context.user_id,
                            GroupChatSubscription.user_id == other_user_id,
                        )).filter(GroupChatSubscription.left == None).join(
                            GroupChat, GroupChat.conversation_id ==
                            GroupChatSubscription.group_chat_id).
                        filter(GroupChat.is_dm == True).group_by(
                            GroupChatSubscription.group_chat_id).having(
                                count == 2).one_or_none()):
                    context.abort(
                        grpc.StatusCode.FAILED_PRECONDITION,
                        "You already have a direct message chat with this user."
                    )

            conversation = Conversation()
            session.add(conversation)

            group_chat = GroupChat(
                conversation=conversation,
                title=request.title.value,
                creator_id=context.user_id,
                is_dm=True
                if len(request.recipient_user_ids) == 1 else False,  # TODO
            )
            session.add(group_chat)

            your_subscription = GroupChatSubscription(
                user_id=context.user_id,
                group_chat=group_chat,
                role=GroupChatRole.admin,
            )
            session.add(your_subscription)

            for recipient in request.recipient_user_ids:
                if get_friends_status(
                        session, context.user_id,
                        recipient) != api_pb2.User.FriendshipStatus.FRIENDS:
                    if len(request.recipient_user_ids) > 1:
                        context.abort(grpc.StatusCode.FAILED_PRECONDITION,
                                      errors.GROUP_CHAT_ONLY_ADD_FRIENDS)
                    else:
                        context.abort(grpc.StatusCode.FAILED_PRECONDITION,
                                      errors.DIRECT_MESSAGE_ONLY_FRIENDS)

                subscription = GroupChatSubscription(
                    user_id=recipient,
                    group_chat=group_chat,
                    role=GroupChatRole.participant,
                )
                session.add(subscription)

            _add_message_to_subscription(session,
                                         your_subscription,
                                         message_type=MessageType.chat_created)

            session.flush()

            return conversations_pb2.GroupChat(
                group_chat_id=group_chat.conversation_id,
                title=group_chat.title,
                member_user_ids=_get_visible_members_for_subscription(
                    your_subscription),
                admin_user_ids=_get_visible_admins_for_subscription(
                    your_subscription),
                only_admins_invite=group_chat.only_admins_invite,
                is_dm=group_chat.is_dm,
                created=Timestamp_from_datetime(
                    group_chat.conversation.created),
            )
Ejemplo n.º 4
0
def add_dummy_users():
    logger.info(f"Adding dummy users")
    with session_scope() as session:
        if session.execute(select(
                func.count()).select_from(User)).scalar_one() > 0:
            logger.info("Users not empty, not adding dummy users")
            return

        with open(SRC_DIR + "/data/dummy_users.json", "r") as f:
            data = json.loads(f.read())

        for user in data["users"]:
            new_user = User(
                username=user["username"],
                email=user["email"],
                hashed_password=hash_password(user["password"])
                if user["password"] else None,
                name=user["name"],
                city=user["location"]["city"],
                geom=create_coordinate(user["location"]["lat"],
                                       user["location"]["lng"]),
                geom_radius=user["location"]["radius"],
                community_standing=user["community_standing"],
                birthdate=date(year=user["birthdate"]["year"],
                               month=user["birthdate"]["month"],
                               day=user["birthdate"]["day"]),
                gender=user["gender"],
                occupation=user["occupation"],
                about_me=user["about_me"],
                about_place=user["about_place"],
                hosting_status=hostingstatus2sql[HostingStatus.Value(
                    user["hosting_status"] if "hosting_status" in
                    user else "HOSTING_STATUS_CANT_HOST")],
                new_notifications_enabled=True,
                accepted_tos=TOS_VERSION,
                accepted_community_guidelines=GUIDELINES_VERSION,
            )
            session.add(new_user)
            session.flush()

            for language in user["languages"]:
                session.add(
                    LanguageAbility(user_id=new_user.id,
                                    language_code=language[0],
                                    fluency=LanguageFluency[language[1]]))
            for region in user["regions_visited"]:
                session.add(
                    RegionVisited(user_id=new_user.id, region_code=region))
            for region in user["regions_lived"]:
                session.add(
                    RegionLived(user_id=new_user.id, region_code=region))

        session.commit()

        for username1, username2 in data["friendships"]:
            friend_relationship = FriendRelationship(
                from_user_id=session.execute(
                    select(User).where(
                        User.username == username1)).scalar_one().id,
                to_user_id=session.execute(
                    select(User).where(
                        User.username == username2)).scalar_one().id,
                status=FriendStatus.accepted,
            )
            session.add(friend_relationship)

        session.commit()

        for reference in data["references"]:
            reference_type = (ReferenceType.hosted
                              if reference["type"] == "hosted" else
                              (ReferenceType.surfed if reference["type"]
                               == "surfed" else ReferenceType.friend))
            new_reference = Reference(
                from_user_id=session.execute(
                    select(User).where(
                        User.username == reference["from"])).scalar_one().id,
                to_user_id=session.execute(
                    select(User).where(
                        User.username == reference["to"])).scalar_one().id,
                reference_type=reference_type,
                text=reference["text"],
                rating=reference["rating"],
                was_appropriate=reference["was_appropriate"],
            )
            session.add(new_reference)

        session.commit()

        for group_chat in data["group_chats"]:
            # Create the chat
            creator = group_chat["creator"]

            conversation = Conversation()
            session.add(conversation)

            chat = GroupChat(
                conversation=conversation,
                title=group_chat["title"],
                creator_id=session.execute(
                    select(User).where(
                        User.username == creator)).scalar_one().id,
                is_dm=group_chat["is_dm"],
            )
            session.add(chat)

            for participant in group_chat["participants"]:
                subscription = GroupChatSubscription(
                    user_id=session.execute(
                        select(User).where(
                            User.username ==
                            participant["username"])).scalar_one().id,
                    group_chat=chat,
                    role=GroupChatRole.admin if participant["username"]
                    == creator else GroupChatRole.participant,
                    joined=parser.isoparse(participant["joined"]),
                )
                session.add(subscription)

            for message in group_chat["messages"]:
                session.add(
                    Message(
                        message_type=MessageType.text,
                        conversation=chat.conversation,
                        author_id=session.execute(
                            select(User).where(
                                User.username ==
                                message["author"])).scalar_one().id,
                        time=parser.isoparse(message["time"]),
                        text=message["message"],
                    ))

        session.commit()