Beispiel #1
0
def submit_review(filecontent, filename, task, user, points, comment="", submit=None):
    if filecontent is None and submit is None:
        raise ValidationError(_("You should upload a file or specify parent submit."))

    if filecontent is not None:
        submit_id = str(int(time()))

        sfiletarget = os.path.join(
            get_path(task, user), "%s-%s-%s" % (user.last_name, submit_id, filename)
        )

        sfiletarget = unidecode(sfiletarget)

        if hasattr(filecontent, "chunks"):
            write_chunks_to_file(sfiletarget, filecontent.chunks())
        else:
            write_chunks_to_file(sfiletarget, [filecontent])
    else:
        sfiletarget = submit.filepath

    sub = Submit(
        task=task,
        user=user,
        points=points,
        submit_type=submit_constants.SUBMIT_TYPE_DESCRIPTION,
        testing_status=submit_constants.SUBMIT_STATUS_REVIEWED,
        filepath=sfiletarget,
        reviewer_comment=comment,
    )
    sub.save()
Beispiel #2
0
    def save(self, req_user, task):
        filecontent = self.cleaned_data["file"]

        path = os.path.join(settings.SUBMIT_PATH, "reviews",
                            "%s_%s.zip" % (int(time()), req_user.username))
        path = unidecode(path)
        write_chunks_to_file(path, filecontent.chunks())
        return path
Beispiel #3
0
 def test_write_chunks_to_file(self):
     # Tests that the directory will be created
     temp_file_path = os.path.join(self.temp_dir, 'dir_to_create', 'tempfile')
     # Tests that we can write both bytes and unicode objects
     # (unicode will be saved with utf-8 encoding)
     write_chunks_to_file(temp_file_path, [u'hello', b'world'])
     with open(temp_file_path, 'rb') as f:
         data = f.read()
         self.assertEqual(data, b'helloworld')
Beispiel #4
0
 def test_write_chunks_to_file(self):
     # Tests that the directory will be created
     temp_file_path = os.path.join(self.temp_dir, "dir_to_create",
                                   "tempfile")
     # Tests that we can write both bytes and unicode objects
     # (unicode will be saved with utf-8 encoding)
     write_chunks_to_file(temp_file_path, ["hello", b"world"])
     with open(temp_file_path, "rb") as f:
         data = f.read()
         self.assertEqual(data, b"helloworld")
Beispiel #5
0
    def save(self, commit=True):
        submit = super(SubmitAdminForm, self).save(commit)
        file = self.cleaned_data.get("submit_file")
        if file:
            user = self.cleaned_data.get("user")
            task = self.cleaned_data.get("task")

            sfiletarget = get_description_file_path(file, user, task)
            write_chunks_to_file(sfiletarget, file.chunks())
            submit.filepath = sfiletarget
        if commit:
            submit.save()
        return submit
Beispiel #6
0
def edit_review(filecontent, filename, submit, user, points, comment=""):
    if filecontent is not None:
        submit_id = str(int(time()))

        sfiletarget = unidecode(
            os.path.join(get_path(submit.task, user),
                         "%s-%s-%s" % (user.last_name, submit_id, filename)))

        if hasattr(filecontent, "chunks"):
            write_chunks_to_file(sfiletarget, filecontent.chunks())
        else:
            write_chunks_to_file(sfiletarget, [filecontent])

        submit.filepath = sfiletarget

    submit.user = user
    submit.points = points
    submit.reviewer_comment = comment
    submit.save()
Beispiel #7
0
def task_submit_post(request, task_id, submit_type):
    """Spracovanie uploadnuteho submitu"""
    try:
        submit_type = int(submit_type)
    except ValueError:
        raise HttpResponseBadRequest

    # Raise Not Found when submitting non existent task
    task = get_object_or_404(Task, pk=task_id)

    # Raise Not Found when submitting non-submittable submit type
    if not task.has_submit_type(submit_type):
        raise Http404

    # Raise Not Found when not submitting through POST
    if request.method != 'POST':
        raise Http404

    try:
        sfile = request.FILES['submit_file']
    except:  # noqa: E722 @FIXME
        # error will be reported from form validation
        pass

    # File will be sent to tester
    if (submit_type == constants.SUBMIT_TYPE_SOURCE
            or submit_type == constants.SUBMIT_TYPE_TESTABLE_ZIP):
        if submit_type == constants.SUBMIT_TYPE_SOURCE:
            form = SourceSubmitForm(request.POST, request.FILES)
        else:
            form = TestableZipSubmitForm(request.POST, request.FILES)
        if form.is_valid():
            if submit_type == constants.SUBMIT_TYPE_SOURCE:
                language = form.cleaned_data['language']
            else:
                language = '.zip'
            # Source submit's should be processed by process_submit()
            submit_id = process_submit(sfile, task, language, request.user)
            if not submit_id:
                messages.add_message(request, messages.ERROR,
                                     'Nepodporovaný formát súboru')
            else:
                # Source file-name is id.data
                sfiletarget = unidecode(
                    os.path.join(
                        get_path(task, request.user),
                        submit_id + constants.SUBMIT_SOURCE_FILE_EXTENSION))
                write_chunks_to_file(sfiletarget, sfile.chunks())
                sub = Submit(task=task,
                             user=request.user,
                             submit_type=submit_type,
                             points=0,
                             filepath=sfiletarget,
                             testing_status=constants.SUBMIT_STATUS_IN_QUEUE,
                             protocol_id=submit_id)
                sub.save()
                if task.email_on_code_submit:
                    send_notification_email(sub, task_id, submit_type)

                success_message = format_html(
                    'Úspešne si submitol program, výsledok testovania nájdeš '
                    '<a href="{}">tu</a>', reverse('view_submit',
                                                   args=[sub.id]))
                messages.add_message(request, messages.SUCCESS,
                                     success_message)
        else:
            for field in form:
                for error in field.errors:
                    messages.add_message(request, messages.ERROR,
                                         '%s: %s' % (field.label, error))
        if 'redirect_to' in request.POST and request.POST['redirect_to']:
            return redirect(request.POST['redirect_to'])
        else:
            return redirect(
                reverse('task_submit_page', kwargs={'task_id': int(task_id)}))

    # File won't be sent to tester
    elif submit_type == constants.SUBMIT_TYPE_DESCRIPTION:
        if request.user.is_competition_ignored(
                task.round.semester.competition):
            return HttpResponseForbidden()
        form = DescriptionSubmitForm(request.POST, request.FILES)
        if form.is_valid():
            sfiletarget = get_description_file_path(sfile, request.user, task)
            write_chunks_to_file(sfiletarget, sfile.chunks())
            sub = Submit(task=task,
                         user=request.user,
                         submit_type=submit_type,
                         points=0,
                         testing_status=constants.SUBMIT_STATUS_IN_QUEUE,
                         filepath=sfiletarget)
            sub.save()
            if task.email_on_desc_submit:
                send_notification_email(sub, task_id, submit_type)

            if task.round.can_submit:
                messages.add_message(
                    request, messages.SUCCESS,
                    _('You have successfully submitted your description, '
                      'it will be reviewed after the round finishes.'))
            else:
                messages.add_message(
                    request, messages.WARNING,
                    _('You have submitted your description after the deadline. '
                      'It is not counted in results.'))
        else:
            for field in form:
                for error in field.errors:
                    messages.add_message(request, messages.ERROR,
                                         '%s: %s' % (field.label, error))

        if 'redirect_to' in request.POST and request.POST['redirect_to']:
            return redirect(request.POST['redirect_to'])
        else:
            return redirect(
                reverse('task_submit_page', kwargs={'task_id': int(task_id)}))

    else:
        # Only Description and Source and Zip submitting is developed currently
        raise Http404
Beispiel #8
0
def task_submit_post(request, task_id, submit_type):
    """Spracovanie uploadnuteho submitu"""
    try:
        submit_type = int(submit_type)
    except ValueError:
        raise HttpResponseBadRequest

    # Raise Not Found when submitting non existent task
    task = get_object_or_404(Task, pk=task_id)

    # Raise Not Found when submitting non-submittable submit type
    if not task.has_submit_type(submit_type):
        raise Http404

    # Raise Not Found when not submitting through POST
    if request.method != "POST":
        raise Http404

    try:
        sfile = request.FILES["submit_file"]
    except:  # noqa: E722 @FIXME
        # error will be reported from form validation
        pass

    # File will be sent to tester
    if (
        submit_type == constants.SUBMIT_TYPE_SOURCE
        or submit_type == constants.SUBMIT_TYPE_TESTABLE_ZIP
    ):
        if submit_type == constants.SUBMIT_TYPE_SOURCE:
            form = SourceSubmitForm(request.POST, request.FILES)
        else:
            form = TestableZipSubmitForm(request.POST, request.FILES)
        if form.is_valid():
            if submit_type == constants.SUBMIT_TYPE_SOURCE:
                language = form.cleaned_data["language"]
            else:
                language = ".zip"
            # Source submit's should be processed by process_submit()
            submit_id = process_submit(sfile, task, language, request.user)
            if not submit_id:
                messages.add_message(request, messages.ERROR, "Nepodporovaný formát súboru")
            else:
                # Source file-name is id.data
                sfiletarget = unidecode(
                    os.path.join(
                        get_path(task, request.user),
                        submit_id + constants.SUBMIT_SOURCE_FILE_EXTENSION,
                    )
                )
                write_chunks_to_file(sfiletarget, sfile.chunks())
                sub = Submit(
                    task=task,
                    user=request.user,
                    submit_type=submit_type,
                    points=0,
                    filepath=sfiletarget,
                    testing_status=constants.SUBMIT_STATUS_IN_QUEUE,
                    protocol_id=submit_id,
                )
                sub.save()
                if task.email_on_code_submit:
                    send_notification_email(sub, task_id, submit_type)

                return redirect(reverse("view_submit", args=[sub.id]))
        else:
            for field in form:
                for error in field.errors:
                    messages.add_message(request, messages.ERROR, "%s: %s" % (field.label, error))
        if "redirect_to" in request.POST and request.POST["redirect_to"]:
            return redirect(request.POST["redirect_to"])
        else:
            return redirect(reverse("task_submit_page", kwargs={"task_id": int(task_id)}))

    # File won't be sent to tester
    elif submit_type == constants.SUBMIT_TYPE_DESCRIPTION:
        if request.user.is_competition_ignored(task.round.semester.competition):
            return HttpResponseForbidden()
        form = DescriptionSubmitForm(request.POST, request.FILES)
        if form.is_valid():
            sfiletarget = get_description_file_path(sfile, request.user, task)
            write_chunks_to_file(sfiletarget, sfile.chunks())
            sub = Submit(
                task=task,
                user=request.user,
                submit_type=submit_type,
                points=0,
                testing_status=constants.SUBMIT_STATUS_IN_QUEUE,
                filepath=sfiletarget,
            )
            sub.save()
            if task.email_on_desc_submit:
                send_notification_email(sub, task_id, submit_type)

            if task.round.can_submit:
                messages.add_message(
                    request,
                    messages.SUCCESS,
                    _(
                        "You have successfully submitted your description, "
                        "it will be reviewed after the round finishes."
                    ),
                )
            else:
                messages.add_message(
                    request,
                    messages.WARNING,
                    _(
                        "You have submitted your description after the deadline. "
                        "It is not counted in results."
                    ),
                )
        else:
            for field in form:
                for error in field.errors:
                    messages.add_message(request, messages.ERROR, "%s: %s" % (field.label, error))

        if "redirect_to" in request.POST and request.POST["redirect_to"]:
            return redirect(request.POST["redirect_to"])
        else:
            return redirect(reverse("task_submit_page", kwargs={"task_id": int(task_id)}))
    else:
        raise Http404