예제 #1
0
    def WriteReference(self, request, context):
        if context.user_id == request.to_user_id:
            context.abort(grpc.StatusCode.INVALID_ARGUMENT,
                          "Can't refer yourself")

        reference = Reference(
            from_user_id=context.user_id,
            to_user_id=request.to_user_id,
            reference_type=reftype2sql[request.reference_type],
            text=request.text,
            was_safe=request.was_safe,
            rating=request.rating,
        )
        with session_scope(self._Session) as session:
            if not session.query(User).filter(
                    User.id == request.to_user_id).one_or_none():
                context.abort(grpc.StatusCode.NOT_FOUND, "User not found")

            if (session.query(Reference).filter(
                    Reference.from_user_id == context.user_id).filter(
                        Reference.to_user_id == request.to_user_id).filter(
                            Reference.reference_type == reftype2sql[
                                request.reference_type]).one_or_none()):
                context.abort(grpc.StatusCode.FAILED_PRECONDITION,
                              "Reference already given")
            session.add(reference)
        return empty_pb2.Empty()
예제 #2
0
파일: api.py 프로젝트: telalpal/couchers
    def WriteReference(self, request, context):
        if context.user_id == request.to_user_id:
            context.abort(grpc.StatusCode.INVALID_ARGUMENT, errors.CANT_REFER_SELF)

        reference = Reference(
            from_user_id=context.user_id,
            to_user_id=request.to_user_id,
            reference_type=reftype2sql[request.reference_type],
            text=request.text,
            was_safe=request.was_safe,
            rating=request.rating,
        )
        with session_scope() as session:
            if not session.query(User).filter(User.id == request.to_user_id).one_or_none():
                context.abort(grpc.StatusCode.NOT_FOUND, errors.USER_NOT_FOUND)

            if (
                session.query(Reference)
                .filter(Reference.from_user_id == context.user_id)
                .filter(Reference.to_user_id == request.to_user_id)
                .filter(Reference.reference_type == reftype2sql[request.reference_type])
                .one_or_none()
            ):
                context.abort(grpc.StatusCode.FAILED_PRECONDITION, errors.REFERENCE_ALREADY_GIVEN)
            session.add(reference)
        return empty_pb2.Empty()
예제 #3
0
    def WriteHostRequestReference(self, request, context):
        with session_scope() as session:
            host_request = (session.query(HostRequest).filter(
                HostRequest.conversation_id == request.host_request_id).filter(
                    or_(HostRequest.from_user_id == context.user_id,
                        HostRequest.to_user_id ==
                        context.user_id)).one_or_none())

            if not host_request:
                context.abort(grpc.StatusCode.NOT_FOUND,
                              errors.HOST_REQUEST_NOT_FOUND)

            if not host_request.can_write_reference:
                context.abort(grpc.StatusCode.FAILED_PRECONDITION,
                              errors.CANT_WRITE_REFERENCE_FOR_REQUEST)

            if (session.query(Reference).filter(
                    Reference.host_request_id == host_request.conversation_id
            ).filter(Reference.from_user_id == context.user_id).one_or_none()):
                context.abort(grpc.StatusCode.FAILED_PRECONDITION,
                              errors.REFERENCE_ALREADY_GIVEN)

            if request.rating < 0 or request.rating > 1:
                context.abort(grpc.StatusCode.INVALID_ARGUMENT,
                              errors.REFERENCE_INVALID_RATING)

            other_reference = (session.query(Reference).filter(
                Reference.host_request_id == host_request.conversation_id
            ).filter(Reference.to_user_id == context.user_id).one_or_none())

            reference = Reference(
                from_user_id=context.user_id,
                host_request_id=host_request.conversation_id,
                text=request.text,
                rating=request.rating,
                was_appropriate=request.was_appropriate,
            )

            if host_request.from_user_id == context.user_id:
                # we requested to surf with someone
                reference.reference_type = ReferenceType.surfed
                reference.to_user_id = host_request.to_user_id
                assert context.user_id == host_request.from_user_id
            else:
                # we hosted someone
                reference.reference_type = ReferenceType.hosted
                reference.to_user_id = host_request.from_user_id
                assert context.user_id == host_request.to_user_id

            session.add(reference)
            session.commit()

            # send the recipient of the reference an email
            send_host_reference_email(reference,
                                      both_written=other_reference is not None)

            return reference_to_pb(reference, context.user_id)
예제 #4
0
def create_friend_reference(session, from_user_id, to_user_id, reference_age):
    reference = Reference(
        time=now() - reference_age,
        from_user_id=from_user_id,
        to_user_id=to_user_id,
        reference_type=ReferenceType.friend,
        text="Test friend request",
        rating=0.4,
        was_appropriate=True,
    )
    session.add(reference)
    session.commit()
    return reference.id
예제 #5
0
def create_host_reference(session,
                          from_user_id,
                          to_user_id,
                          reference_age,
                          *,
                          surfing=True,
                          host_request_id=None):
    if host_request_id:
        actual_host_request_id = host_request_id
    else:
        if surfing:
            actual_host_request_id = host_request_id or create_host_request(
                session, from_user_id, to_user_id,
                reference_age - timedelta(days=1))
        else:
            actual_host_request_id = host_request_id or create_host_request(
                session, to_user_id, from_user_id,
                reference_age - timedelta(days=1))

    host_request = session.query(HostRequest).filter(
        HostRequest.conversation_id == actual_host_request_id).one()

    other_reference = (session.query(Reference).filter(
        Reference.host_request_id == host_request.conversation_id).filter(
            Reference.to_user_id == from_user_id).one_or_none())

    reference = Reference(
        time=now() - reference_age,
        from_user_id=from_user_id,
        host_request_id=host_request.conversation_id,
        text="Dummy reference",
        rating=0.5,
        was_appropriate=True,
    )

    if host_request.from_user_id == from_user_id:
        reference.reference_type = ReferenceType.surfed
        reference.to_user_id = host_request.to_user_id
        assert from_user_id == host_request.from_user_id
    else:
        reference.reference_type = ReferenceType.hosted
        reference.to_user_id = host_request.from_user_id
        assert from_user_id == host_request.to_user_id

    session.add(reference)
    session.commit()
    return reference.id, actual_host_request_id
예제 #6
0
def create_host_reference(session,
                          from_user_id,
                          to_user_id,
                          reference_age,
                          *,
                          surfing=True,
                          host_request_id=None):
    if host_request_id:
        actual_host_request_id = host_request_id
    else:
        if surfing:
            actual_host_request_id = host_request_id or create_host_request(
                session, from_user_id, to_user_id,
                reference_age + timedelta(days=1))
        else:
            actual_host_request_id = host_request_id or create_host_request(
                session, to_user_id, from_user_id,
                reference_age + timedelta(days=1))

    host_request = session.execute(
        select(HostRequest).where(HostRequest.conversation_id ==
                                  actual_host_request_id)).scalar_one()

    reference = Reference(
        time=now() - reference_age,
        from_user_id=from_user_id,
        host_request_id=host_request.conversation_id,
        text="Dummy reference",
        rating=0.5,
        was_appropriate=True,
    )

    if host_request.surfer_user_id == from_user_id:
        reference.reference_type = ReferenceType.surfed
        reference.to_user_id = host_request.host_user_id
        assert from_user_id == host_request.surfer_user_id
    else:
        reference.reference_type = ReferenceType.hosted
        reference.to_user_id = host_request.surfer_user_id
        assert from_user_id == host_request.host_user_id

    session.add(reference)
    session.commit()
    return reference.id, actual_host_request_id
예제 #7
0
def test_reference_report_email(db):
    with session_scope() as session:
        from_user, api_token_author = generate_user()
        to_user, api_token_reported = generate_user()

        friend_relationship = FriendRelationship(from_user=from_user, to_user=to_user, status=FriendStatus.accepted)
        session.add(friend_relationship)
        session.flush()

        reference = Reference(
            from_user=from_user,
            to_user=to_user,
            reference_type=ReferenceType.friend,
            text="This person was not nice to me.",
            rating=0.3,
            was_appropriate=False,
        )

        with patch("couchers.email.queue_email") as mock:
            maybe_send_reference_report_email(reference)

        assert mock.call_count == 1

        (sender_name, sender_email, recipient, subject, plain, html), _ = mock.call_args
        assert recipient == "*****@*****.**"
        assert "report" in subject.lower()
        assert "reference" in subject.lower()
        assert reference.from_user.username in plain
        assert str(reference.from_user.id) in plain
        assert reference.from_user.email in plain
        assert reference.from_user.username in html
        assert str(reference.from_user.id) in html
        assert reference.from_user.email in html
        assert reference.to_user.username in plain
        assert str(reference.to_user.id) in plain
        assert reference.to_user.email in plain
        assert reference.to_user.username in html
        assert str(reference.to_user.id) in html
        assert reference.to_user.email in html
        assert reference.text in plain
        assert reference.text in html
        assert "friend" in plain.lower()
        assert "friend" in html.lower()
예제 #8
0
    def WriteFriendReference(self, request, context):
        if context.user_id == request.to_user_id:
            context.abort(grpc.StatusCode.INVALID_ARGUMENT,
                          errors.CANT_REFER_SELF)

        with session_scope() as session:
            check_valid_reference(request, context)

            if not session.execute(
                    select(User).where_users_visible(context).where(
                        User.id == request.to_user_id)).scalar_one_or_none():
                context.abort(grpc.StatusCode.NOT_FOUND, errors.USER_NOT_FOUND)

            if session.execute(
                    select(Reference).where(
                        Reference.from_user_id == context.user_id).where(
                            Reference.to_user_id == request.to_user_id).where(
                                Reference.reference_type ==
                                ReferenceType.friend)).scalar_one_or_none():
                context.abort(grpc.StatusCode.FAILED_PRECONDITION,
                              errors.REFERENCE_ALREADY_GIVEN)

            reference = Reference(
                from_user_id=context.user_id,
                to_user_id=request.to_user_id,
                reference_type=ReferenceType.friend,
                text=request.text.strip(),
                private_text=request.private_text.strip(),
                rating=request.rating,
                was_appropriate=request.was_appropriate,
            )
            session.add(reference)
            session.commit()

            # send the recipient of the reference an email
            send_friend_reference_email(reference)

            # possibly send out an alert to the mod team if the reference was bad
            maybe_send_reference_report_email(reference)

            return reference_to_pb(reference, context)
예제 #9
0
    def WriteFriendReference(self, request, context):
        if context.user_id == request.to_user_id:
            context.abort(grpc.StatusCode.INVALID_ARGUMENT,
                          errors.CANT_REFER_SELF)

        with session_scope() as session:
            if not session.query(User).filter(
                    User.id == request.to_user_id).one_or_none():
                context.abort(grpc.StatusCode.NOT_FOUND, errors.USER_NOT_FOUND)

            if (session.query(Reference).filter(
                    Reference.from_user_id == context.user_id).filter(
                        Reference.to_user_id == request.to_user_id).filter(
                            Reference.reference_type ==
                            ReferenceType.friend).one_or_none()):
                context.abort(grpc.StatusCode.FAILED_PRECONDITION,
                              errors.REFERENCE_ALREADY_GIVEN)

            if request.rating < 0 or request.rating > 1:
                context.abort(grpc.StatusCode.INVALID_ARGUMENT,
                              errors.REFERENCE_INVALID_RATING)

            reference = Reference(
                from_user_id=context.user_id,
                to_user_id=request.to_user_id,
                reference_type=ReferenceType.friend,
                text=request.text,
                rating=request.rating,
                was_appropriate=request.was_appropriate,
            )
            session.add(reference)
            session.commit()

            # send the recipient of the reference an email
            send_friend_reference_email(reference)

            return reference_to_pb(reference, context.user_id)
예제 #10
0
def test_reference_report_email_not_sent(db):
    with session_scope() as session:
        from_user, api_token_author = generate_user()
        to_user, api_token_reported = generate_user()

        friend_relationship = FriendRelationship(from_user=from_user, to_user=to_user, status=FriendStatus.accepted)
        session.add(friend_relationship)
        session.flush()

        reference = Reference(
            from_user=from_user,
            to_user=to_user,
            reference_type=ReferenceType.friend,
            text="This person was very nice to me.",
            rating=0.9,
            was_appropriate=True,
        )

        # no email sent for a positive ref

        with patch("couchers.email.queue_email") as mock:
            maybe_send_reference_report_email(reference)

        assert mock.call_count == 0
예제 #11
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?")
예제 #12
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()
예제 #13
0
    def WriteHostRequestReference(self, request, context):
        with session_scope() as session:
            check_valid_reference(request, context)

            host_request = session.execute(
                select(HostRequest).where_users_column_visible(
                    context,
                    HostRequest.surfer_user_id).where_users_column_visible(
                        context, HostRequest.host_user_id).
                where(HostRequest.conversation_id ==
                      request.host_request_id).where(
                          or_(HostRequest.surfer_user_id == context.user_id,
                              HostRequest.host_user_id ==
                              context.user_id))).scalar_one_or_none()

            if not host_request:
                context.abort(grpc.StatusCode.NOT_FOUND,
                              errors.HOST_REQUEST_NOT_FOUND)

            if not host_request.can_write_reference:
                context.abort(grpc.StatusCode.FAILED_PRECONDITION,
                              errors.CANT_WRITE_REFERENCE_FOR_REQUEST)

            if session.execute(
                    select(Reference).where(
                        Reference.host_request_id ==
                        host_request.conversation_id).where(
                            Reference.from_user_id ==
                            context.user_id)).scalar_one_or_none():
                context.abort(grpc.StatusCode.FAILED_PRECONDITION,
                              errors.REFERENCE_ALREADY_GIVEN)

            other_reference = session.execute(
                select(Reference).where(
                    Reference.host_request_id == host_request.conversation_id).
                where(Reference.to_user_id ==
                      context.user_id)).scalar_one_or_none()

            reference = Reference(
                from_user_id=context.user_id,
                host_request_id=host_request.conversation_id,
                text=request.text.strip(),
                private_text=request.private_text.strip(),
                rating=request.rating,
                was_appropriate=request.was_appropriate,
            )

            if host_request.surfer_user_id == context.user_id:
                # we requested to surf with someone
                reference.reference_type = ReferenceType.surfed
                reference.to_user_id = host_request.host_user_id
                assert context.user_id == host_request.surfer_user_id
            else:
                # we hosted someone
                reference.reference_type = ReferenceType.hosted
                reference.to_user_id = host_request.surfer_user_id
                assert context.user_id == host_request.host_user_id

            session.add(reference)
            session.commit()

            # send the recipient of the reference an email
            send_host_reference_email(reference,
                                      both_written=other_reference is not None)

            # possibly send out an alert to the mod team if the reference was bad
            maybe_send_reference_report_email(reference)

            return reference_to_pb(reference, context)