示例#1
0
    def test_lazy_user(self):
        u = User.objects.create_user("Lars Bak", "*****@*****.**", "x864lyfe")
        PlayerStat.objects.create(user=u, points=5001)
        badges.possibly_award_badge("points_awarded", user=u)
        self.assertEqual(u.badges_earned.count(), 1)

        self.assert_num_queries(1, lambda: u.badges_earned.get().badge)
示例#2
0
文件: views.py 项目: chaosk/teerace
def register(request):
    if request.user.is_authenticated:
        return redirect(reverse("home"))

    _request = None
    if request.method == "POST":
        _request = request.POST.copy()
    else:
        _request = request.GET.copy()
    next_uri = _request.get(
        "next", get_config("FIRST_LOGIN_REDIRECT_URL", reverse("first_steps"))
    )
    # rescuing poor users from infinite redirection loop
    if not next_uri or next_uri == get_config("LOGIN_URL", reverse("login")):
        next_uri = get_config("FIRST_LOGIN_REDIRECT_URL", reverse("first_steps"))

    register_form = RegisterForm()

    if request.method == "POST":
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            register_form.save()
            username = register_form.cleaned_data["username"]
            password = register_form.cleaned_data["password1"]
            user = authenticate(username=username, password=password)
            if user is not None:
                auth_login(request, user)
                messages.success(request, "Welcome aboard, {0}.".format(user))
                badges.possibly_award_badge("logged_in", user=user)
            return redirect(next_uri)

    return {"register_form": register_form, "next": next_uri}
    def handle(self, *args, **options):  # noqa: C901

        vote_type = ContentType.objects.get_for_model(Vote)
        for vote in Vote.objects.all():
            badges.possibly_award_badge('vote_cast', user=vote.author)
            if not Action.objects.filter(
                    action_object_content_type_id=vote_type.id,
                    action_object_object_id=vote.id):
                actions_when_vote_created(vote)

        conversation_type = ContentType.objects.get_for_model(Conversation)
        for conversation in Conversation.objects.all():
            if not Action.objects.filter(
                    action_object_content_type_id=conversation_type.id,
                    action_object_object_id=conversation.id,
                    verb='created conversation'):
                actions_when_conversation_created(conversation)

        comment_type = ContentType.objects.get_for_model(Comment)
        for comment in Comment.objects.all():
            if not Action.objects.filter(
                    action_object_content_type_id=comment_type.id,
                    action_object_object_id=comment.id):
                actions_when_comment_saved(comment)

        user_type = ContentType.objects.get_for_model(get_user_model())
        for user in get_user_model().objects.all():
            if not Action.objects.filter(
                    action_object_content_type_id=user_type.id,
                    action_object_object_id=user.id,
                    verb='user created'):
                actions_when_user_created(user)
                if user.profile_filled:
                    actions_when_user_profile_filled(user)
示例#4
0
def register(request):
    if request.user.is_authenticated:
        return redirect(reverse("home"))

    _request = None
    if request.method == "POST":
        _request = request.POST.copy()
    else:
        _request = request.GET.copy()
    next_uri = _request.get(
        "next", get_config("FIRST_LOGIN_REDIRECT_URL", reverse("first_steps"))
    )
    # rescuing poor users from infinite redirection loop
    if next_uri == get_config("LOGIN_URL", reverse("login")):
        next_uri = get_config("FIRST_LOGIN_REDIRECT_URL", reverse("first_steps"))

    register_form = RegisterForm()

    if request.method == "POST":
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            register_form.save()
            username = register_form.cleaned_data["username"]
            password = register_form.cleaned_data["password1"]
            user = authenticate(username=username, password=password)
            if user is not None:
                auth_login(request, user)
                messages.success(request, "Welcome aboard, {0}.".format(user))
                badges.possibly_award_badge("logged_in", user=user)
            return redirect(next_uri)

    return {"register_form": register_form, "next": next_uri}
示例#5
0
文件: views.py 项目: chaosk/teerace
def login(request):
    if request.user.is_authenticated:
        return redirect(reverse("home"))

    _request = None
    if request.method == "POST":
        _request = request.POST.copy()
    else:
        _request = request.GET.copy()

    next_uri = _request.get("next", get_config("LOGIN_REDIRECT_URL", reverse("home")))
    # rescuing poor users from infinite redirection loop
    if next_uri == get_config("LOGIN_URL", reverse("login")):
        next_uri = get_config("LOGIN_REDIRECT_URL", reverse("home"))

    login_form = LoginForm()

    if request.method == "POST":
        login_form = LoginForm(request.POST)
        if login_form.is_valid() and login_form.user:
            auth_login(request, login_form.user)
            messages.success(request, "Hello, {0}.".format(login_form.user))
            badges.possibly_award_badge("logged_in", user=login_form.user)
            return redirect(next_uri)

    return {"login_form": login_form, "next": next_uri}
示例#6
0
 def setUp(self):
     self.user = User.objects.create_user("Lars Bak", "*****@*****.**",
                                          "x864lyfe")
     PlayerStat.objects.create(user=self.user)
     self.user.stats.points += 5001
     self.user.stats.save()
     badges.possibly_award_badge("points_awarded", user=self.user)
示例#7
0
def login(request):
    if request.user.is_authenticated:
        return redirect(reverse("home"))

    _request = None
    if request.method == "POST":
        _request = request.POST.copy()
    else:
        _request = request.GET.copy()

    next_uri = _request.get("next", get_config("LOGIN_REDIRECT_URL", reverse("home")))
    # rescuing poor users from infinite redirection loop
    if next_uri == get_config("LOGIN_URL", reverse("login")):
        next_uri = get_config("LOGIN_REDIRECT_URL", reverse("home"))

    login_form = LoginForm()

    if request.method == "POST":
        login_form = LoginForm(request.POST)
        if login_form.is_valid() and login_form.user:
            auth_login(request, login_form.user)
            messages.success(request, "Hello, {0}.".format(login_form.user))
            badges.possibly_award_badge("logged_in", user=login_form.user)
            return redirect(next_uri)

    return {"login_form": login_form, "next": next_uri}
示例#8
0
def actions_when_user_profile_filled(instance):
    action.send(instance,
                verb='filled profile',
                description=_('Filled Profile'),
                action_object=instance,
                target=instance)
    badges.possibly_award_badge("user_profile_filled", user=instance)
    award_points(instance, 'user_profile_filled')
示例#9
0
def actions_when_user_created(instance):
    action.send(instance,
                verb='user created',
                description=_('Was Created'),
                action_object=instance,
                target=instance,
                timestamp=instance.date_joined)
    badges.possibly_award_badge("user_created", user=instance)
    award_points(instance, 'user_created', reason="User Created")
示例#10
0
def actions_when_vote_created(instance):
    award_points(instance.author,
                 'voted',
                 reason="Voted on Conversation",
                 source=instance)

    if instance.value == Vote.AGREE:
        action.send(instance.author,
                    verb='agreed with',
                    description=_('Agreed With'),
                    action_object=instance,
                    target=instance.comment,
                    timestamp=instance.created_at)

    if instance.value == Vote.PASS:
        action.send(instance.author,
                    verb='passed on',
                    description=_('Passed On'),
                    action_object=instance,
                    target=instance.comment,
                    timestamp=instance.created_at)

    if instance.value == Vote.DISAGREE:
        action.send(instance.author,
                    verb='disagreed with',
                    description=_('Disagreed With'),
                    action_object=instance,
                    target=instance.comment,
                    timestamp=instance.created_at)

    # Let's find out whether vote is in a new conversation
    conversations = Conversation.objects.filter(
        comments__votes__author=instance.author,
        comments__votes__created_at__lte=instance.created_at).distinct(
        ).annotate(number_of_votes=Count('comments__votes'))
    number_of_first_votes = sum(
        [x.number_of_votes for x in conversations if x.number_of_votes == 1])
    if len(conversations) == 2 and number_of_first_votes >= 1:
        award_points(instance.author,
                     'voted_first_time_in_second_conversation',
                     reason='Voted first time in second conversation',
                     source=instance)
    if len(conversations) > 2 and number_of_first_votes >= 1:
        award_points(instance.author,
                     'voted_first_time_in_new_conversation_after_second',
                     reason='Voted first time in new conversation',
                     source=instance)

    # And finally, the badges
    badges.possibly_award_badge('vote_cast', user=instance.author)
示例#11
0
    def mark_complete(self):
        """
        Marks this game as complete and unlocks the next game (or module)
        :raises: NoMoreEntitiesException if this is the last game in the last module
        """
        if self.status == self.STATUS.COMPLETE:
            return

        self.user.profile.award_points(1)
        badges.possibly_award_badge("points_awarded", user=self.user)

        self.status = self.STATUS.COMPLETE
        self.save()
        try:
            self.unlock_next_game()
        except NoMoreEntitiesException:
            self.user_game_module.mark_complete()
示例#12
0
文件: views.py 项目: chaosk/teerace
 def post(self, request, format=None):
     filtered_checkpoints = get_filtered_checkpoints(request.data["checkpoints"])
     user_id = request.data.get("user_id")
     user = get_object_or_404(User, pk=user_id) if user_id else None
     run = Run(
         map_id=int(request.data["map_id"]),
         server=request.auth,
         user=user,
         nickname=request.data["nickname"],
         clan=request.data.get("clan", ""),
         time=Decimal(request.data["time"]),
         checkpoints=filtered_checkpoints,
     )
     run.save()
     tasks.redo_ranks.apply(args=[run.id])
     if user is not None:
         user.profile.update_connection(request.auth)
         badges.possibly_award_badge("run_finished", user=user, run=run)
     return Response(serializers.RunSerializer(run).data)
示例#13
0
 def post(self, request, format=None):
     filtered_checkpoints = get_filtered_checkpoints(
         request.data["checkpoints"])
     user_id = request.data.get("user_id")
     user = get_object_or_404(User, pk=user_id) if user_id else None
     run = Run(
         map_id=int(request.data["map_id"]),
         server=request.auth,
         user_id=user_id,
         nickname=request.data["nickname"],
         clan=request.data["clan"],
         time=request.data["time"],
         checkpoints=filtered_checkpoints,
     )
     run.save()
     tasks.redo_ranks.apply(args=[run.id])
     if user is not None:
         user.profile.update_connection(request.auth)
         badges.possibly_award_badge("run_finished", user=user, run=run)
     return Response(serializers.RunSerializer(run).data)
示例#14
0
    def test_award(self):
        u = User.objects.create_user("Lars Bak", "*****@*****.**", "x864lyfe")
        PlayerStat.objects.create(user=u)
        badges.possibly_award_badge("points_awarded", user=u)
        self.assertEqual(u.badges_earned.count(), 0)

        u.stats.points += 5001
        u.stats.save()
        badges.possibly_award_badge("points_awarded", user=u)
        self.assertEqual(u.badges_earned.count(), 1)
        self.assertEqual(u.badges_earned.all()[0].badge.name, "Bronze")

        badges.possibly_award_badge("points_awarded", user=u)
        self.assertEqual(u.badges_earned.count(), 1)

        u.stats.points += 2500
        badges.possibly_award_badge("points_awarded", user=u)
        self.assertEqual(u.badges_earned.count(), 2)
示例#15
0
def redo_ranks(run_id):
    from pinax.badges.registry import badges

    logger = redo_ranks.get_logger()
    try:
        user_run = Run.objects.get(pk=run_id)
    except Run.DoesNotExist:
        logger.error("[R- /U- /M- ] Run not found (pk={0}).".format(run_id))
        return False
    map_obj = user_run.map
    if user_run.user is None:
        logger.info(
            "[R-{0}/U- /M-{1}] Anonymous run, not"
            " processing the rank.".format(run_id, map_obj.id)
        )
        return
    user_best = BestRun.objects.get(map=map_obj, user=user_run.user)
    if not user_best.run_id == user_run.id:
        logger.info(
            "[R-{0}/U-{1}/M-{2}] Not best run,"
            " not processing the rank.".format(run_id, user_run.user_id, map_obj.id)
        )
        return
    runs = BestRun.objects.filter(map=map_obj)
    # ranked = player that receives points for his place
    ranked_count = len(BestRun.SCORING)
    # exclude banned users from scoring
    ranked = runs.exclude(user__is_active=False)[:ranked_count]
    try:
        if user_run.time >= ranked[ranked_count - 1].run.time:
            logger.info(
                "[R-{0}/U-{1}/M-{2}] Run won't affect scoring,"
                " not processing the rank.".format(run_id, user_run.user_id, map_obj.id)
            )
            return
    except IndexError:
        pass
    old_rank = user_run.user.profile.map_position(map_obj.id)
    new_rank = None
    i = 0
    for run in ranked:
        run.points = BestRun.SCORING[i]
        run.save()
        # FIXME it's 3 AM, sorry for that
        run.user.profile.points = (
            BestRun.objects.filter(user=run.user).aggregate(Sum("points"))[
                "points__sum"
            ]
            or 0
        )
        run.user.profile.save()
        i += 1
        if user_run.user_id == run.user_id:
            new_rank = i
    runs.exclude(id__in=ranked.values_list("id", flat=True)).update(points=0)
    badges.possibly_award_badge("rank_processed", user=user_run.user)
    logger.info(
        "[R-{0}/U-{1}/M-{2}] {3}'s new map rank is {4} (was: {5}).".format(
            run_id, user_run.user_id, map_obj.id, user_run.user, new_rank, old_rank
        )
    )
示例#16
0
文件: tasks.py 项目: chaosk/teerace
def redo_ranks(run_id):
    from pinax.badges.registry import badges

    logger = redo_ranks.get_logger()
    try:
        user_run = Run.objects.get(pk=run_id)
    except Run.DoesNotExist:
        logger.error("[R- /U- /M- ] Run not found (pk={0}).".format(run_id))
        return False
    map_obj = user_run.map
    if user_run.user is None:
        logger.info(
            "[R-{0}/U- /M-{1}] Anonymous run, not"
            " processing the rank.".format(run_id, map_obj.id)
        )
        return
    user_best = BestRun.objects.get(map=map_obj, user=user_run.user)
    if not user_best.run_id == user_run.id:
        logger.info(
            "[R-{0}/U-{1}/M-{2}] Not best run,"
            " not processing the rank.".format(run_id, user_run.user_id, map_obj.id)
        )
        return
    runs = BestRun.objects.filter(map=map_obj)
    # ranked = player that receives points for his place
    ranked_count = len(BestRun.SCORING)
    # exclude banned users from scoring
    ranked = runs.exclude(user__is_active=False)[:ranked_count]
    try:
        if user_run.time >= ranked[ranked_count - 1].run.time:
            logger.info(
                "[R-{0}/U-{1}/M-{2}] Run won't affect scoring,"
                " not processing the rank.".format(run_id, user_run.user_id, map_obj.id)
            )
            return
    except IndexError:
        pass
    old_rank = user_run.user.profile.map_position(map_obj.id)
    new_rank = None
    i = 0
    for run in ranked:
        run.points = BestRun.SCORING[i]
        run.save()
        # FIXME it's 3 AM, sorry for that
        run.user.profile.points = (
            BestRun.objects.filter(user=run.user).aggregate(Sum("points"))[
                "points__sum"
            ]
            or 0
        )
        run.user.profile.save()
        i += 1
        if user_run.user_id == run.user_id:
            new_rank = i
    runs.exclude(id__in=ranked.values_list("id", flat=True)).update(points=0)
    badges.possibly_award_badge("rank_processed", user=user_run.user)
    logger.info(
        "[R-{0}/U-{1}/M-{2}] {3}'s new map rank is {4} (was: {5}).".format(
            run_id, user_run.user_id, map_obj.id, user_run.user, new_rank, old_rank
        )
    )