Example #1
0
def join_contest(request, key):
    contest, exists = _find_contest(request, key)
    if not exists:
        return contest

    if not contest.can_join:
        return generic_message(request, 'Contest not ongoing',
                               '"%s" is not currently ongoing.' % contest.name)

    contest_profile = request.user.profile.contest
    if contest_profile.current is not None:
        return generic_message(request, 'Already in contest',
                               'You are already in a contest: "%s".' % contest_profile.current.contest.name)

    participation, created = ContestParticipation.objects.get_or_create(
        contest=contest, profile=contest_profile, defaults={
            'real_start': timezone.now()
        }
    )

    if not created and participation.ended:
        return generic_message(request, 'Time limit exceeded',
                               'Too late! You already used up your time limit for "%s".' % contest.name)

    contest_profile.current = participation
    contest_profile.save()
    return HttpResponseRedirect(reverse('problem_list'))
Example #2
0
 def handle(self, request, org, profile):
     if profile.organizations.filter(id=org.id).exists():
         return generic_message(request, _('Joining organization'), _('You are already in the organization.'))
     if not org.is_open:
         return generic_message(request, _('Joining organization'), _('This organization is not open.'))
     profile.organizations.add(org)
     profile.save()
     cache.delete(make_template_fragment_key('org_member_count', (org.id,)))
Example #3
0
 def dispatch(self, request, *args, **kwargs):
     profile = request.user.profile
     if profile.points < 50:
         return generic_message(request, "Can't add organization",
                                'You need 50 points to add an organization.')
     elif profile.organization is not None:
         return generic_message(request, "Can't add organization",
                                'You are already in an organization.')
     return super(NewOrganization, self).dispatch(request, *args, **kwargs)
Example #4
0
 def handle(self, request, org, profile):
     if profile.organization_id is not None:
         return generic_message(request, 'Joining organization', 'You are already in an organization.')
     if not org.is_open:
         return generic_message(request, 'Joining organization', 'This organization is not open.')
     profile.organization = org
     profile.organization_join_time = timezone.now()
     profile.save()
     cache.delete(make_template_fragment_key('org_member_count', (org.id,)))
Example #5
0
 def dispatch(self, request, *args, **kwargs):
     try:
         return super(ContestMixin, self).dispatch(request, *args, **kwargs)
     except Http404:
         key = kwargs.get(self.slug_url_kwarg, None)
         if key:
             return generic_message(request, 'No such contest',
                                    'Could not find a contest with the key "%s".' % key)
         else:
             return generic_message(request, 'No such contest',
                                    'Could not find such contest.')
Example #6
0
 def dispatch(self, request, *args, **kwargs):
     try:
         return super(OrganizationMixin, self).dispatch(request, *args, **kwargs)
     except Http404:
         key = kwargs.get(self.slug_url_kwarg, None)
         if key:
             return generic_message(request, _('No such organization'),
                                    _('Could not find an organization with the key "%s".') % key)
         else:
             return generic_message(request, _('No such organization'),
                                    _('Could not find such organization.'))
Example #7
0
    def handle(self, request, org, profile):
        if profile.organizations.filter(id=org.id).exists():
            return generic_message(request, _('Joining organization'), _('You are already in the organization.'))

        if not org.is_open:
            return generic_message(request, _('Joining organization'), _('This organization is not open.'))

        max_orgs = getattr(settings, 'DMOJ_USER_MAX_ORGANIZATION_COUNT', 3)
        if profile.organizations.filter(is_open=True).count() >= max_orgs:
            return generic_message(request, _('Joining organization'), _('You may not be part of more than {count} public organizations.').format(count=max_orgs))

        profile.organizations.add(org)
        profile.save()
        cache.delete(make_template_fragment_key('org_member_count', (org.id,)))
Example #8
0
 def dispatch(self, request, *args, **kwargs):
     try:
         return super(ContestMixin, self).dispatch(request, *args, **kwargs)
     except Http404:
         key = kwargs.get(self.slug_url_kwarg, None)
         if key:
             return generic_message(request, _('No such contest'),
                                    _('Could not find a contest with the key "%s".') % key)
         else:
             return generic_message(request, _('No such contest'),
                                    _('Could not find such contest.'))
     except PrivateContestError as e:
         return render(request, 'contest/private.html', {
             'orgs': e.orgs, 'title': _('Access to contest "%s" denied') % escape(e.name)
         }, status=403)
Example #9
0
 def get(self, request, *args, **kwargs):
     name = request.GET.get('target') if 'target' in request.GET else None
     try:
         self.target = Profile.objects.get(user__username=self.target)
     except ObjectDoesNotExist:
         return generic_message(request, 'No such user', 'No user called "%s"' % name)
     return super(NewMessage, self).get(request, *args, **kwargs)
Example #10
0
 def handle(self, request, org, profile):
     if org.id != profile.organization_id:
         return generic_message(request, 'Leaving organization', 'You are not in "%s".' % org.key)
     profile.organization = None
     profile.organization_join_time = None
     profile.save()
     cache.delete(make_template_fragment_key('org_member_count', (org.id,)))
Example #11
0
File: problem.py Project: DMOJ/site
    def get(self, request, *args, **kwargs):
        self.setup(request)

        try:
            return super(ProblemList, self).get(request, *args, **kwargs)
        except ProgrammingError as e:
            return generic_message(request, 'FTS syntax error', e.args[1], status=400)
Example #12
0
 def get(self, request, *args, **kwargs):
     try:
         return super(ProblemMixin, self).get(request, *args, **kwargs)
     except Http404:
         code = kwargs.get(self.slug_url_kwarg, None)
         return generic_message(request, _('No such problem'),
                                _('Could not find a problem with the code "%s".') % code, status=404)
Example #13
0
 def dispatch(self, request, *args, **kwargs):
     try:
         return super(JudgeDetail, self).dispatch(request, *args, **kwargs)
     except Http404:
         key = kwargs.get(self.slug_url_kwarg, None)
         return generic_message(request, _('No such judge'),
                                _('Could not find a judge with the name "%s".') % key)
Example #14
0
 def dispatch(self, request, *args, **kwargs):
     try:
         return super(LanguageDetail, self).dispatch(request, *args, **kwargs)
     except Http404:
         key = kwargs.get(self.slug_url_kwarg, None)
         return generic_message(request, 'No such language',
                                'Could not find a language with the key "%s".' % key)
Example #15
0
    def get(self, request, *args, **kwargs):
        contest = self.get_object()
        if not contest.can_join:
            return generic_message(request, _('Contest not ongoing'),
                                   _('"%s" is not currently ongoing.') % contest.name)

        profile = request.user.profile
        if profile.current_contest is not None:
            return generic_message(request, _('Already in contest'),
                                   _('You are already in a contest: "%s".') % profile.current_contest.contest.name)

        if contest.ended:
            while True:
                virtual_id = (ContestParticipation.objects.filter(contest=contest, user=profile)
                              .aggregate(virtual_id=Max('virtual'))['virtual_id'] or 0) + 1
                try:
                    participation = ContestParticipation.objects.create(
                        contest=contest, user=profile, virtual=virtual_id,
                        real_start=timezone.now()
                    )
                # There is obviously a race condition here, so we keep trying until we win the race.
                except IntegrityError:
                    pass
                else:
                    break
        else:
            participation, created = ContestParticipation.objects.get_or_create(
                contest=contest, user=profile, virtual=(-1 if profile in contest.organizers.all() else 0),
                defaults={
                    'real_start': timezone.now()
                }
            )

            if not created and participation.ended:
                participation = ContestParticipation.objects.get_or_create(
                    contest=contest, user=profile, virtual=-1,
                    defaults={
                        'real_start': timezone.now()
                    }
                )[0]

        profile.current_contest = participation
        profile.save()
        contest._updating_stats_only = True
        contest.update_user_count()
        return HttpResponseRedirect(reverse('problem_list'))
Example #16
0
def _find_contest(request, key, private_check=True):
    try:
        contest = Contest.objects.get(key=key)
        if private_check and not contest.is_accessible_by(request.user):
            raise ObjectDoesNotExist()
    except ObjectDoesNotExist:
        return generic_message(request, _('No such contest'),
                               _('Could not find a contest with the key "%s".') % key, status=404), False
    return contest, True
Example #17
0
def _find_contest(request, key, private_check=True):
    try:
        contest = Contest.objects.get(key=key)
        if private_check and not contest.is_public and not request.user.has_perm('judge.see_private_contest'):
            raise ObjectDoesNotExist()
    except ObjectDoesNotExist:
        return generic_message(request, 'No such contest',
                               'Could not find a contest with the key "%s".' % key, status=404), False
    return contest, True
Example #18
0
 def dispatch(self, request, *args, **kwargs):
     if self.kwargs.get(self.slug_url_kwarg, None) is None:
         if not self.request.user.is_authenticated():
             return redirect_to_login(self.request.get_full_path())
     try:
         return super(UserPage, self).dispatch(request, *args, **kwargs)
     except Http404:
         return generic_message(request, 'No such user', 'No user handle "%s".' %
                                self.kwargs.get(self.slug_url_kwarg, None))
Example #19
0
    def post(self, request, *args, **kwargs):
        organization = self.get_object()
        if not self.can_edit_organization(organization):
            return generic_message(request, _("Can't edit organization"),
                                   _('You are not allowed to kick people from this organization.'), status=403)

        try:
            user = Profile.objects.get(id=request.POST.get('user', None))
        except Profile.DoesNotExist:
            return generic_message(request, _("Can't kick user"),
                                   _('The user you are trying to kick does not exist!'), status=400)

        if not organization.members.filter(id=user.id).exists():
            return generic_message(request, _("Can't kick user"),
                                   _('The user you are trying to kick is not in organization: %s.') %
                                   organization.name, status=400)

        organization.members.remove(user)
        return HttpResponseRedirect(organization.get_users_url())
Example #20
0
    def post(self, request, *args, **kwargs):
        contest = self.get_object()

        profile = request.user.profile
        if profile.current_contest is None or profile.current_contest.contest_id != contest.id:
            return generic_message(request, _('No such contest'),
                                   _('You are not in contest "%s".') % contest.key, 404)

        profile.remove_contest()
        return HttpResponseRedirect(reverse('contest_view', args=(contest.key,)))
Example #21
0
    def get(self, request, *args, **kwargs):
        contest = self.get_object()

        contest_profile = request.user.profile.contest
        if contest_profile.current is None or contest_profile.current.contest != contest:
            return generic_message(request, 'No such contest',
                                   'You are not in contest "%s".' % contest.key, 404)
        contest_profile.current = None
        contest_profile.save()
        return HttpResponseRedirect(reverse('contest_view', args=(contest.key,)))
Example #22
0
    def get(self, request, *args, **kwargs):
        self.setup(request)

        order = request.GET.get('order', '')
        if not ((not order.startswith('-') or order.count('-') == 1) and (order.lstrip('-') in self.all_sorts)):
            order = 'code'
        self.order = order
        try:
            return super(ProblemList, self).get(request, *args, **kwargs)
        except ProgrammingError as e:
            return generic_message(request, 'FTS syntax error', e.args[1], status=400)
Example #23
0
def _find_contest(request, key, private_check=True):
    try:
        contest = Contest.objects.get(key=key)
        if private_check and not contest.is_public and not request.user.has_perm('judge.see_private_contest') and (
                not request.user.has_perm('judge.edit_own_contest') or
                not contest.organizers.filter(id=request.user.profile.id).exists()):
            raise ObjectDoesNotExist()
    except ObjectDoesNotExist:
        return generic_message(request, _('No such contest'),
                               _('Could not find a contest with the key "%s".') % key, status=404), False
    return contest, True
Example #24
0
def leave_contest(request, key):
    # No public checking because if we hide the contest people should still be able to leave.
    # No lock ins.
    contest, exists = _find_contest(request, key, False)
    if not exists:
        return contest

    contest_profile = request.user.profile.contest
    if contest_profile.current is None or contest_profile.current.contest != contest:
        return generic_message(request, 'No such contest',
                               'You are not in contest "%s".' % key, 404)
    contest_profile.current = None
    contest_profile.save()
    return HttpResponseRedirect(reverse('contest_view', args=(key,)))
Example #25
0
 def dispatch(self, request, *args, **kwargs):
     try:
         return super(EditOrganization, self).dispatch(request, *args, **kwargs)
     except PermissionDenied:
         return generic_message(request, _("Can't edit organization"),
                                _('You are not allowed to edit this organization.'), status=403)
Example #26
0
 def handle(self, request, org, profile):
     if not profile.organizations.filter(id=org.id).exists():
         return generic_message(request, _('Leaving organization'), _('You are not in "%s".') % org.key)
     profile.organizations.remove(org)
     cache.delete(make_template_fragment_key('org_member_count', (org.id,)))
Example #27
0
    def join_contest(self, request, access_code=None):
        contest = self.object

        if not contest.can_join and not (self.is_editor or self.is_tester):
            return generic_message(
                request, _('Contest not ongoing'),
                _('"%s" is not currently ongoing.') % contest.name)

        profile = request.profile
        if profile.current_contest is not None:
            return generic_message(
                request, _('Already in contest'),
                _('You are already in a contest: "%s".') %
                profile.current_contest.contest.name)

        if not request.user.is_superuser and contest.banned_users.filter(
                id=profile.id).exists():
            return generic_message(
                request, _('Banned from joining'),
                _('You have been declared persona non grata for this contest. '
                  'You are permanently barred from joining this contest.'))

        requires_access_code = (not self.can_edit and contest.access_code
                                and access_code != contest.access_code)
        if contest.ended:
            if requires_access_code:
                raise ContestAccessDenied()

            while True:
                virtual_id = max((ContestParticipation.objects.filter(
                    contest=contest, user=profile).aggregate(
                        virtual_id=Max('virtual'))['virtual_id'] or 0) + 1, 1)
                try:
                    participation = ContestParticipation.objects.create(
                        contest=contest,
                        user=profile,
                        virtual=virtual_id,
                        real_start=timezone.now(),
                    )
                # There is obviously a race condition here, so we keep trying until we win the race.
                except IntegrityError:
                    pass
                else:
                    break
        else:
            SPECTATE = ContestParticipation.SPECTATE
            LIVE = ContestParticipation.LIVE
            try:
                participation = ContestParticipation.objects.get(
                    contest=contest,
                    user=profile,
                    virtual=(SPECTATE
                             if self.is_editor or self.is_tester else LIVE),
                )
            except ContestParticipation.DoesNotExist:
                if requires_access_code:
                    raise ContestAccessDenied()

                participation = ContestParticipation.objects.create(
                    contest=contest,
                    user=profile,
                    virtual=(SPECTATE
                             if self.is_editor or self.is_tester else LIVE),
                    real_start=timezone.now(),
                )
            else:
                if participation.ended:
                    participation = ContestParticipation.objects.get_or_create(
                        contest=contest,
                        user=profile,
                        virtual=SPECTATE,
                        defaults={'real_start': timezone.now()},
                    )[0]

        profile.current_contest = participation
        profile.save()
        contest._updating_stats_only = True
        contest.update_user_count()
        return HttpResponseRedirect(reverse('problem_list'))
Example #28
0
 def dispatch(self, request, *args, **kwargs):
     try:
         return super(EditOrganization, self).dispatch(request, *args, **kwargs)
     except PermissionDenied:
         return generic_message(request, _("Can't edit organization"),
                                _('You are not allowed to edit this organization.'), status=403)
Example #29
0
File: problem.py Project: DMOJ/site
 def no_such_problem(self):
     code = self.kwargs.get(self.slug_url_kwarg, None)
     return generic_message(self.request, _('No such problem'),
                            _('Could not find a problem with the code "%s".') % code, status=404)
Example #30
0
 def no_such_problem(self):
     code = self.kwargs.get(self.slug_url_kwarg, None)
     return generic_message(self.request, _('No such problem'),
                            _('Could not find a problem with the code "%s".') % code, status=404)
Example #31
0
 def handle(self, request, org, profile):
     if not profile.organizations.filter(id=org.id).exists():
         return generic_message(request, _('Leaving organization'), _('You are not in "%s".') % org.short_name)
     profile.organizations.remove(org)
     cache.delete(make_template_fragment_key('org_member_count', (org.id,)))
Example #32
0
def problem_submit(request, problem=None, submission=None):
    if submission is not None and not request.user.has_perm('judge.resubmit_other') and \
                    get_object_or_404(Submission, id=int(submission)).user.user != request.user:
        raise PermissionDenied()

    profile = request.user.profile
    if request.method == 'POST':
        form = ProblemSubmitForm(request.POST,
                                 instance=Submission(user=profile))
        if form.is_valid():
            if (not request.user.has_perm('judge.spam_submission')
                    and Submission.objects.filter(
                        user=profile, was_rejudged=False).exclude(
                            status__in=['D', 'IE', 'CE', 'AB']).count() > 2):
                return HttpResponse(
                    '<h1>You submitted too many submissions.</h1>', status=503)
            if not form.cleaned_data['problem'].allowed_languages.filter(
                    id=form.cleaned_data['language'].id).exists():
                raise PermissionDenied()
            if not form.cleaned_data['problem'].is_accessible_by(request.user):
                user_logger.info(
                    'Naughty user %s wants to submit to %s without permission',
                    request.user.username, form.cleaned_data['problem'].code)
                return HttpResponseForbidden(
                    '<h1>Do you want me to ban you?</h1>')
            if not request.user.is_superuser and form.cleaned_data[
                    'problem'].banned_users.filter(id=profile.id).exists():
                return generic_message(
                    request, _('Banned from Submitting'),
                    _('You have been declared persona non grata for this problem. '
                      'You are permanently barred from submitting this problem.'
                      ))
            model = form.save()

            profile.update_contest()
            if profile.current_contest is not None:
                try:
                    contest_problem = model.problem.contests.get(
                        contest=profile.current_contest.contest)
                except ContestProblem.DoesNotExist:
                    pass
                else:
                    contest = ContestSubmission(
                        submission=model,
                        problem=contest_problem,
                        participation=profile.current_contest)
                    contest.save()

            model.judge()
            return HttpResponseRedirect(
                reverse('submission_status', args=[str(model.id)]))
        else:
            form_data = form.cleaned_data
    else:
        initial = {'language': profile.language}
        if problem is not None:
            initial['problem'] = get_object_or_404(Problem, code=problem)
            if not initial['problem'].is_accessible_by(request.user):
                raise Http404()
        if submission is not None:
            try:
                sub = get_object_or_404(Submission, id=int(submission))
                initial['source'] = sub.source
                initial['language'] = sub.language
            except ValueError:
                raise Http404()
        form = ProblemSubmitForm(initial=initial)
        form_data = initial
    if 'problem' in form_data:
        form.fields['language'].queryset = (
            form_data['problem'].usable_languages.order_by(
                'name', 'key').prefetch_related(
                    Prefetch('runtimeversion_set',
                             RuntimeVersion.objects.order_by('priority'))))
    if 'language' in form_data:
        form.fields['source'].widget.mode = form_data['language'].ace
    form.fields['source'].widget.theme = profile.ace_theme
    return render(
        request, 'problem/submit.jade', {
            'form': form,
            'title': _('Submit'),
            'langs': Language.objects.all(),
            'no_judges': not form.fields['language'].queryset,
            'ACE_URL': ACE_URL
        })
Example #33
0
def problem_submit(request, problem=None, submission=None):
    if submission is not None and not request.user.has_perm('judge.resubmit_other') and \
                    get_object_or_404(Submission, id=int(submission)).user.user != request.user:
        raise PermissionDenied()

    profile = request.user.profile
    if request.method == 'POST':
        form = ProblemSubmitForm(request.POST, instance=Submission(user=profile))
        if form.is_valid():
            if (not request.user.has_perm('judge.spam_submission') and
                        Submission.objects.filter(user=profile, is_being_rejudged=False).exclude(
                            status__in=['D', 'IE', 'CE', 'AB']).count() > 2):
                return HttpResponse('<h1>You submitted too many submissions.</h1>', status=503)
            if not form.cleaned_data['problem'].allowed_languages.filter(
                    id=form.cleaned_data['language'].id).exists():
                raise PermissionDenied()
            if not form.cleaned_data['problem'].is_accessible_by(request.user):
                user_logger.info('Naughty user %s wants to submit to %s without permission',
                                 request.user.username, form.cleaned_data['problem'].code)
                return HttpResponseForbidden('<h1>Do you want me to ban you?</h1>')
            if not request.user.is_superuser and form.cleaned_data['problem'].banned_users.filter(
                    id=profile.id).exists():
                return generic_message(request, _('Banned from Submitting'),
                                       _('You have been declared persona non grata for this problem. '
                                         'You are permanently barred from submitting this problem.'))
            model = form.save()

            profile.update_contest()
            if profile.current_contest is not None:
                try:
                    contest_problem = model.problem.contests.get(contest=profile.current_contest.contest)
                except ContestProblem.DoesNotExist:
                    pass
                else:
                    contest = ContestSubmission(submission=model, problem=contest_problem,
                                                participation=profile.current_contest)
                    contest.save()

            model.judge()
            return HttpResponseRedirect(reverse('submission_status', args=[str(model.id)]))
        else:
            form_data = form.cleaned_data
    else:
        initial = {'language': profile.language}
        if problem is not None:
            initial['problem'] = get_object_or_404(Problem, code=problem)
            if not initial['problem'].is_accessible_by(request.user):
                raise Http404()
        if submission is not None:
            try:
                sub = get_object_or_404(Submission, id=int(submission))
                initial['source'] = sub.source
                initial['language'] = sub.language
            except ValueError:
                raise Http404()
        form = ProblemSubmitForm(initial=initial)
        form_data = initial
    if 'problem' in form_data:
        form.fields['language'].queryset = (form_data['problem'].usable_languages.order_by('name', 'key')
                                            .prefetch_related(
            Prefetch('runtimeversion_set', RuntimeVersion.objects.order_by('priority'))))
    if 'language' in form_data:
        form.fields['source'].widget.mode = form_data['language'].ace
    form.fields['source'].widget.theme = profile.ace_theme
    return render(request, 'problem/submit.jade', {
        'form': form,
        'title': _('Submit'),
        'langs': Language.objects.all(),
        'no_judges': not form.fields['language'].queryset,
        'ACE_URL': ACE_URL
    })
Example #34
0
    def join_contest(self, request, access_code=None):
        contest = self.object

        if not contest.can_join and not self.is_organizer:
            return generic_message(request, _('Contest not ongoing'),
                                   _('"%s" is not currently ongoing.') % contest.name)

        profile = request.user.profile
        if profile.current_contest is not None:
            return generic_message(request, _('Already in contest'),
                                   _('You are already in a contest: "%s".') % profile.current_contest.contest.name)

        if not request.user.is_superuser and contest.banned_users.filter(id=profile.id).exists():
            return generic_message(request, _('Banned from joining'),
                                   _('You have been declared persona non grata for this contest. '
                                     'You are permanently barred from joining this contest.'))

        requires_access_code = not (request.user.is_superuser or self.is_organizer) \
                               and contest.access_code and access_code != contest.access_code
        if contest.ended:
            if requires_access_code:
                raise ContestAccessDenied()

            while True:
                virtual_id = (ContestParticipation.objects.filter(contest=contest, user=profile)
                              .aggregate(virtual_id=Max('virtual'))['virtual_id'] or 0) + 1
                try:
                    participation = ContestParticipation.objects.create(
                        contest=contest, user=profile, virtual=virtual_id,
                        real_start=timezone.now()
                    )
                # There is obviously a race condition here, so we keep trying until we win the race.
                except IntegrityError:
                    pass
                else:
                    break
        else:
            try:
                participation = ContestParticipation.objects.get(
                    contest=contest, user=profile, virtual=(-1 if self.is_organizer else 0)
                )
            except ContestParticipation.DoesNotExist:
                if requires_access_code:
                    raise ContestAccessDenied()

                participation = ContestParticipation.objects.create(
                    contest=contest, user=profile, virtual=(-1 if self.is_organizer else 0),
                    real_start=timezone.now(),
                )
            else:
                if participation.ended:
                    participation = ContestParticipation.objects.get_or_create(
                        contest=contest, user=profile, virtual=-1,
                        defaults={
                            'real_start': timezone.now()
                        }
                    )[0]

        profile.current_contest = participation
        profile.save()
        contest._updating_stats_only = True
        contest.update_user_count()
        return HttpResponseRedirect(reverse('problem_list'))
Example #35
0
def problem_submit(request, problem=None, submission=None):
    try:
        if submission is not None and not request.user.has_perm('judge.resubmit_other') and \
                Submission.objects.get(id=int(submission)).user.user != request.user:
            raise PermissionDenied()
    except Submission.DoesNotExist:
        raise Http404()

    profile = request.user.profile
    if request.method == 'POST':
        form = ProblemSubmitForm(request.POST,
                                 instance=Submission(user=profile))
        if form.is_valid():
            if (not request.user.has_perm('judge.spam_submission')
                    and Submission.objects.filter(
                        user=profile, is_being_rejudged=False).exclude(
                            status__in=['D', 'IE', 'CE', 'AB']).count() > 2):
                return HttpResponse(
                    '<h1>You submitted too many submissions.</h1>', status=503)
            if not form.cleaned_data['problem'].allowed_languages.filter(
                    id=form.cleaned_data['language'].id).exists():
                raise PermissionDenied()
            if not request.user.is_superuser and form.cleaned_data[
                    'problem'].banned_users.filter(id=profile.id).exists():
                return generic_message(
                    request, _('Banned from Submitting'),
                    _('You have been declared persona non grata for this problem. '
                      'You are permanently barred from submitting this problem.'
                      ))
            model = form.save()

            cp = profile.contest
            if cp.current is not None:
                try:
                    contest_problem = model.problem.contests.get(
                        contest=cp.current.contest)
                except ContestProblem.DoesNotExist:
                    pass
                else:
                    contest = ContestSubmission(submission=model,
                                                problem=contest_problem,
                                                participation=cp.current)
                    contest.save()

            model.judge()
            return HttpResponseRedirect(
                reverse('submission_status', args=[str(model.id)]))
        else:
            form_data = form.cleaned_data
    else:
        initial = {'language': profile.language}
        if problem is not None:
            try:
                initial['problem'] = Problem.objects.get(code=problem)
            except ObjectDoesNotExist:
                raise Http404()
            if not initial['problem'].is_accessible_by(request.user):
                raise Http404()
        if submission is not None:
            try:
                sub = Submission.objects.get(id=int(submission))
                initial['source'] = sub.source
                initial['language'] = sub.language
            except (ObjectDoesNotExist, ValueError):
                raise Http404()
        form = ProblemSubmitForm(initial=initial)
        form_data = initial
    if 'problem' in form_data:
        form.fields['language'].queryset = form_data[
            'problem'].usable_languages.order_by('name', 'key')
    if 'language' in form_data:
        form.fields['source'].widget.mode = form_data['language'].ace
    form.fields['source'].widget.theme = profile.ace_theme
    return render(
        request, 'problem/submit.jade', {
            'form': form,
            'title': _('Submit'),
            'langs': Language.objects.all(),
            'no_judges': not form.fields['language'].queryset
        })
Example #36
0
 def get(self, request, *args, **kwargs):
     try:
         return super(ProblemDetail, self).get(request, *args, **kwargs)
     except Http404:
         code = kwargs.get(self.slug_url_kwarg, None)
         return generic_message(request, 'No such problem', 'Could not find a problem with the code "%s".' % code)
Example #37
0
def problem_submit(request, problem=None, submission=None):
    if submission is not None and not request.user.has_perm('judge.resubmit_other') and \
                    get_object_or_404(Submission, id=int(submission)).user.user != request.user:
        raise PermissionDenied()

    profile = request.user.profile
    
    # Contest accounts should not be able to submit outside of contests
    if profile.current_contest is None and profile.is_contest_account:
        raise PermissionDenied()

    if request.method == 'POST':
        form = ProblemSubmitForm(request.POST, instance=Submission(user=profile))
        if form.is_valid():
            if (not request.user.has_perm('judge.spam_submission') and
                        Submission.objects.filter(user=profile, was_rejudged=False).exclude(
                            status__in=['D', 'IE', 'CE', 'AB']).count() > 2):
                return HttpResponse('<h1>You submitted too many submissions.</h1>', status=503)
            if not form.cleaned_data['problem'].allowed_languages.filter(
                    id=form.cleaned_data['language'].id).exists():
                raise PermissionDenied()
            if not form.cleaned_data['problem'].is_accessible_by(request.user):
                user_logger.info('Naughty user %s wants to submit to %s without permission',
                                 request.user.username, form.cleaned_data['problem'].code)
                return HttpResponseForbidden('<h1>Do you want me to ban you?</h1>')
            if not request.user.is_superuser and form.cleaned_data['problem'].banned_users.filter(
                    id=profile.id).exists():
                return generic_message(request, _('Banned from submitting'),
                                       _('You have been declared persona non grata for this problem. '
                                         'You are permanently barred from submitting this problem.'))

            if profile.current_contest is not None:
                try:
                    contest_problem = form.cleaned_data['problem'].contests.get(contest=profile.current_contest.contest)
                except ContestProblem.DoesNotExist:
                    model = form.save()
                else:
                    max_subs = contest_problem.max_submissions
                    if max_subs and get_contest_submission_count(problem, profile) >= max_subs:
                        return generic_message(request, _('Too many submissions'),
                                                _('You have exceeded the submission limit for this problem.'))
                    model = form.save()
                    contest = ContestSubmission(submission=model, problem=contest_problem,
                                                participation=profile.current_contest)
                    contest.save()
            else:
                model = form.save()

            profile.update_contest()
            model.judge(rejudge=False)
            return HttpResponseRedirect(reverse('submission_status', args=[str(model.id)]))
        else:
            form_data = form.cleaned_data
            if submission is not None:
                sub = get_object_or_404(Submission, id=int(submission))
    else:
        initial = {'language': profile.language}
        if problem is not None:
            initial['problem'] = get_object_or_404(Problem, code=problem)
            problem_object = initial['problem']
            if not problem_object.is_accessible_by(request.user):
                raise Http404()
        if submission is not None:
            try:
                sub = get_object_or_404(Submission, id=int(submission))
                initial['source'] = sub.source
                initial['language'] = sub.language
            except ValueError:
                raise Http404()
        form = ProblemSubmitForm(initial=initial)
        form_data = initial
    if 'problem' in form_data:
        form.fields['language'].queryset = (form_data['problem'].usable_languages.order_by('name', 'key')
            .prefetch_related(Prefetch('runtimeversion_set', RuntimeVersion.objects.order_by('priority'))))
        problem_object = form_data['problem']
    if 'language' in form_data:
        form.fields['source'].widget.mode = form_data['language'].ace
    form.fields['source'].widget.theme = profile.ace_theme

    if submission is not None:
        default_lang = sub.language
    else:
        default_lang = request.user.profile.language

    submission_limit = submissions_left = None
    if profile.current_contest is not None:
        try:
            submission_limit = problem_object.contests.get(contest=profile.current_contest.contest).max_submissions
        except ContestProblem.DoesNotExist:
            pass
        else:
            if submission_limit:
                submissions_left = submission_limit - get_contest_submission_count(problem, profile)
    return render(request, 'problem/submit.html', {
        'form': form,
        'title': _('Submit to %(problem)s') % {
            'problem': problem_object.translated_name(request.LANGUAGE_CODE),
        },
        'content_title': mark_safe(escape(_('Submit to %(problem)s')) % {
            'problem': format_html(u'<a href="{0}">{1}</a>',
                                   reverse('problem_detail', args=[problem_object.code]),
                                   problem_object.translated_name(request.LANGUAGE_CODE))
        }),
        'langs': Language.objects.all(),
        'no_judges': not form.fields['language'].queryset,
        'submission_limit': submission_limit,
        'submissions_left': submissions_left,
        'ACE_URL': ACE_URL,

        'default_lang': default_lang,
    })