Example #1
0
def handle_file_post(request, copyedit):
    """
    Handles uploading of copyediting files, checks a file has been selected and a label has been entered, Assigs the
    file to the CopyeditAssignment.
    :param request: HttpRequest
    :param copyedit: CopyeditAssignment object
    :return: None or a list of errors
    """
    errors = []
    file = request.FILES.get('file')
    file_label = request.POST.get('label')

    if not file:
        errors.append('You must select a file.')
    if not file_label:
        errors.append('You must add a label for your file.')

    if not errors:
        new_file = files.save_file_to_article(file,
                                              copyedit.article,
                                              request.user,
                                              label=file_label)
        copyedit.copyeditor_files.add(new_file)
        return None
    else:
        return errors
Example #2
0
def save_galley(article, request, uploaded_file, is_galley, label, is_other):
    new_file = files.save_file_to_article(uploaded_file, article, request.user)
    new_file.is_galley = is_galley
    new_file.label = label

    if is_other:
        article.data_figure_files.add(new_file)
    else:
        article.manuscript_files.add(new_file)

    new_file.save()
    article.save()

    if new_file.mime_type == 'text/html':
        type = 'html'
        label = 'HTML'
    elif new_file.mime_type == 'application/xml':
        type = 'xml'
        label = 'XML'
    else:
        type = label.lower()

    new_galley = core_models.Galley.objects.create(
        article=article,
        file=new_file,
        label=label,
        type=type,
        sequence=article.get_next_galley_sequence())

    return new_galley
Example #3
0
def import_galleys(article, layout_dict, client, owner=None):
    galleys = list()
    if not owner:
        owner = article.owner

    if layout_dict.get('galleys'):
        for galley in layout_dict.get('galleys'):
            logger.info('Adding Galley with label {label}'.format(
                label=galley.get('label')))
            if not galley.get("file") or galley["file"] == "None":
                logger.warning("Can't fetch galley: %s", galley)
                continue
            remote_file = client.fetch_file(galley.get("file"),
                                            galley.get("label"))
            galley_file = core_files.save_file_to_article(
                remote_file, article, owner, label=galley.get("label"))

            new_galley, c = core_models.Galley.objects.get_or_create(
                article=article,
                type=GALLEY_TYPES.get(galley.get("label"), "other"),
                defaults={
                    "label": galley.get("label"),
                    "file": galley_file,
                },
            )
            if c:
                galleys.append(new_galley)

    return galleys
Example #4
0
def save_galley(article,
                request,
                uploaded_file,
                is_galley,
                label,
                save_to_disk=True):
    new_file = files.save_file_to_article(uploaded_file,
                                          article,
                                          request.user,
                                          save=save_to_disk)
    new_file.is_galley = is_galley
    new_file.label = label

    new_file.save()
    article.save()

    if new_file.mime_type == 'text/html':
        type = 'html'
        label = 'HTML'
    elif new_file.mime_type == 'application/xml':
        type = 'xml'
        label = 'XML'
    else:
        type = label.lower()

    new_galley = core_models.Galley.objects.create(
        article=article,
        file=new_file,
        label=label,
        type=type,
        sequence=article.get_next_galley_sequence())

    return new_galley
Example #5
0
def save_galley(article, request, uploaded_file, is_galley, label=None, save_to_disk=True):
    new_file = files.save_file_to_article(uploaded_file, article, request.user, save=save_to_disk)
    new_file.is_galley = is_galley
    new_file.label = label

    new_file.save()
    article.save()

    if new_file.mime_type in files.HTML_MIMETYPES:
        type = 'html'
        label = 'HTML'
        with open(new_file.self_article_path(), 'r+') as f:
            html_contents = f.read()
            f.seek(0)
            cleaned_html = remove_css_from_html(html_contents)
            f.write(cleaned_html)
            f.truncate()

    elif new_file.mime_type in files.XML_MIMETYPES:
        type = 'xml'
        label = 'XML'
    elif label is None:
        raise TypeError("Invalid file %s" % (new_file.mime_type))
    else:
        type = label.lower()

    new_galley = core_models.Galley.objects.create(
        article=article, file=new_file, label=label, type=type, sequence=article.get_next_galley_sequence()
    )

    return new_galley
Example #6
0
def save_galley_image(galley,
                      request,
                      uploaded_file,
                      label="Galley Image",
                      fixed=False):

    if fixed:
        filename = request.POST.get('file_name')
        uploaded_file_mime = files.check_in_memory_mime(uploaded_file)
        expected_mime = files.guess_mime(filename)

        if not uploaded_file_mime == expected_mime:
            messages.add_message(
                request, messages.WARNING,
                'The file you uploaded does not match the mime of the '
                'file expected.')

    new_file = files.save_file_to_article(uploaded_file, galley.article,
                                          request.user)
    new_file.is_galley = False
    new_file.label = label

    if fixed:
        new_file.original_filename = request.POST.get('file_name')

    new_file.save()

    galley.images.add(new_file)

    return new_file
Example #7
0
def handle_author_post(request, preprint):
    file = request.FILES.get('file')
    update_type = request.POST.get('upload_type')
    galley_id = request.POST.get('galley_id')
    galley = get_object_or_404(core_models.Galley,
                               article=preprint,
                               pk=galley_id)

    if request.press.preprint_pdf_only and not files.check_in_memory_mime(
            in_memory_file=file) == 'application/pdf':
        messages.add_message(request, messages.WARNING,
                             'You must upload a PDF file.')
        return
    else:
        file = files.save_file_to_article(file,
                                          preprint,
                                          request.user,
                                          label=galley.label)

    models.VersionQueue.objects.create(article=preprint,
                                       galley=galley,
                                       file=file,
                                       update_type=update_type)

    messages.add_message(
        request, messages.INFO,
        'This update has been added to the moderation queue.')
Example #8
0
def article_file(uploaded_file, article, request):
    new_file = files.save_file_to_article(uploaded_file, article, request.user)
    new_file.label = 'Banner image'
    new_file.description = 'Banner image'
    new_file.privacy = 'public'
    new_file.save()
    return new_file
Example #9
0
def save_prod_file(article, request, uploaded_file, label):
    new_file = files.save_file_to_article(uploaded_file, article, request.user)
    new_file.label = label
    new_file.is_galley = False
    new_file.save()

    article.manuscript_files.add(new_file)
Example #10
0
def save_source_file(article, request, uploaded_file):
    new_file = files.save_file_to_article(uploaded_file, article, request.user)
    new_file.label = "Source File"
    new_file.is_galley = False
    new_file.save()

    article.source_files.add(new_file)
Example #11
0
def handle_review_comment(article, review_obj, comment, form):
    element = form.elements.filter(kind="textarea", name="Review").first()
    if element:
        soup = BeautifulSoup(comment, "html.parser")
        for tag in soup.find_all(["br", "p"]):
            tag.replace_with("\n" + tag.text)
        comment = soup.text
        answer, _ = review_models.ReviewAssignmentAnswer.objects.get_or_create(
            assignment=review_obj,
            element=element,
        )
        answer.answer = comment
        answer.save()
    else:
        comment = linebreaksbr(comment)
        filepath = core_files.create_temp_file(comment,
                                               'comment-from-ojs.html')
        f = open(filepath, 'r')
        comment_file = core_files.save_file_to_article(
            f,
            article,
            article.owner,
            label='Review Comments',
            save=False,
        )

        review_obj.review_file = comment_file

    return review_obj
Example #12
0
def save_supp_file(article, request, uploaded_file, label):
    new_file = files.save_file_to_article(uploaded_file, article, request.user)
    new_file.label = label
    new_file.is_galley = False
    new_file.save()

    supp_file = core_models.SupplementaryFile.objects.create(file=new_file)

    article.supplementary_files.add(supp_file)
Example #13
0
def author_update_file(request, article_id, author_review_id, file_id):
    """
    Allows an article's author to update a copyeditor_file
    :param request: django request object
    :param article_id: Article pk
    :param author_review_id: AuthorReview pk
    :param file_id: File pk
    :return: contextualised django template
    """
    author_review = get_object_or_404(models.AuthorReview,
                                      pk=author_review_id,
                                      assignment__article__id=article_id,
                                      date_decided__isnull=True)
    copyedit = author_review.assignment

    try:
        file = copyedit.copyeditor_files.get(pk=file_id)
    except core_models.File.DoesNotExist:
        raise Http404

    if request.POST and request.FILES:

        if 'replacement' in request.POST:
            uploaded_file = request.FILES.get('replacement-file')
            label = request.POST.get('label')
            new_file = files.save_file_to_article(uploaded_file,
                                                  copyedit.article,
                                                  request.user,
                                                  replace=file,
                                                  is_galley=False,
                                                  label=label)
            files.replace_file(copyedit.article,
                               file,
                               new_file,
                               copyedit=copyedit,
                               retain_old_label=False)
            author_review.files_updated.add(new_file)

        return redirect(
            reverse('author_copyedit',
                    kwargs={
                        'article_id': article_id,
                        'author_review_id': author_review.pk
                    }))

    if request.GET.get('file_id'):
        return logic.attempt_to_serve_file(request, copyedit)

    template = 'copyediting/author_update_file.html'
    context = {
        'author_review': author_review,
        'copyedit': copyedit,
        'file': file,
    }

    return render(request, template, context)
Example #14
0
def save_galley(article,
                request,
                uploaded_file,
                is_galley,
                label=None,
                save_to_disk=True):
    new_file = files.save_file_to_article(
        uploaded_file,
        article,
        request.user,
        save=save_to_disk,
    )
    new_file.is_galley = is_galley
    new_file.label = label

    new_file.save()
    article.save()

    type_ = None

    if new_file.mime_type in files.HTML_MIMETYPES:
        type_ = 'html'
        if not label:
            label = 'HTML'

        with open(new_file.self_article_path(), 'r+', encoding="utf-8") as f:
            html_contents = f.read()
            f.seek(0)
            cleaned_html = remove_css_from_html(html_contents)
            f.write(cleaned_html)
            f.truncate()

    elif new_file.mime_type in files.XML_MIMETYPES:
        type_ = 'xml'
        if not label:
            label = 'XML'
    elif new_file.mime_type in files.PDF_MIMETYPES:
        type_ = 'pdf'
        if not label:
            label = 'PDF'

    if not label:
        label = 'Other'
    if not type_:
        type_ = 'other'

    new_galley = core_models.Galley.objects.create(
        article=article,
        file=new_file,
        label=label,
        type=type_,
        sequence=article.get_next_galley_sequence(),
    )

    return new_galley
Example #15
0
def save_galley_css(galley, request, uploaded_file, filename, label="Galley Image"):
    new_file = files.save_file_to_article(uploaded_file, galley.article, request.user)
    new_file.is_galley = False
    new_file.label = label
    new_file.original_filename = filename
    new_file.save()

    galley.css_file = new_file
    galley.save()

    return new_file
Example #16
0
def replace_galley_file(article, request, galley, uploaded_file):
    if uploaded_file:
        new_file = files.save_file_to_article(uploaded_file, article, request.user)
        new_file.is_galley = True
        new_file.label = galley.file.label
        new_file.parent = galley.file
        new_file.save()
        galley.file = new_file
        galley.save()
    else:
        messages.add_message(request, messages.WARNING, 'No file was selected.')
Example #17
0
def handle_annotated_galley_upload(request, proofing_task, article):
    uploaded_files = request.FILES.getlist('file')

    if uploaded_files:
        for file in uploaded_files:
            new_file = files.save_file_to_article(file, article, request.user)
            new_file.label = 'Annotated Proof'
            new_file.save()
            proofing_task.proofed_files.add(new_file)
            messages.add_message(request, messages.SUCCESS, 'Annotated file uploaded.')
        return None
    else:
        return 'uploadbox'
Example #18
0
def add_supp_file_to_article(supp_file, file_soup, article, label=None):
    if not label and file_soup.description:
        label = file_soup.description.string
    else:
        label = "Supplementary File"

    saved_file = files.save_file_to_article(
        supp_file, article,
        owner=None,
        label=label,
        is_galley=False,
    )
    supp_obj = SupplementaryFile.objects.create(file=saved_file)
    article.supplementary_files.add(supp_obj)
    return supp_obj
Example #19
0
def add_html_galley(html_galley, article):
    if article.galley_set.filter(type="html").exists():
        return
    saved_file = files.save_file_to_article(
            html_galley, article,
            owner=None,
            label="HTML",
            is_galley=True,
    )
    galley = Galley.objects.create(
            article=article,
            file=saved_file,
            type="html",
            label="HTML",
    )
    article.galley_set.add(galley)
Example #20
0
def handle_zipped_galley_images(zip_file, galley, request):

    with zipfile.ZipFile(zip_file, 'r') as zf:
        for finfo in zf.infolist():
            zipped_file = zf.open(finfo)
            content_file = ContentFile(zipped_file.read())
            content_file.name = zipped_file.name

            if zipped_file.name in galley.has_missing_image_files():
                new_file = files.save_file_to_article(
                    content_file,
                    galley.article,
                    request.user,
                )
                new_file.is_galley = False
                new_file.label = "Galley Image"
                new_file.save()

                galley.images.add(new_file)

            elif zipped_file.name in galley.all_images():
                try:
                    file = galley.images.get(
                        original_filename=zipped_file.name, )

                    updated_file = files.overwrite_file(
                        content_file, file, ('articles', galley.article.pk))
                    updated_file.original_filename = zipped_file.name
                    updated_file.save()

                    messages.add_message(
                        request, messages.SUCCESS,
                        'New version of {} saved.'.format(zipped_file.name))
                except core_models.File.DoesNotExist:
                    messages.add_message(
                        request, messages.ERROR,
                        'A file was found in XML and Zip but no corresponding'
                        'File object could be found. {}'.format(
                            zipped_file.name, ))

                messages.add_message(request, messages.SUCCESS, '')
            else:
                messages.add_message(
                    request, messages.WARNING,
                    'File {} not found in XML'.format(zipped_file.name))
    return
Example #21
0
    def sync_galleys(self, article, metadata):
        """currently only supporting pdf galleys"""
        for document in metadata["documents"]:
            if document["mime_type"] in files.PDF_MIMETYPES:
                file_data = document["files"][0]  # PDFs have always one file
                response = requests.get(file_data["uri"], stream=True)
                validate_response(response)
                file_ = SimpleUploadedFile(
                    file_data["filename"],
                    response.content,
                    document["mime_type"],
                )

                if article.pdfs:
                    if len(article.pdfs) > 1:
                        raise RuntimeError("Article has multiple PDF galleys")
                    files.overwrite_file(
                        file_,
                        article.pdfs[0].file,
                        'articles',
                        article.pk,
                    )
                else:
                    saved_file = files.save_file_to_article(
                        file_,
                        article,
                        owner=None,
                        label="pdf",
                        is_galley=True,
                    )
                    galley = Galley.objects.create(
                        article=article,
                        file=saved_file,
                        type="pdf",
                        label="PDF",
                    )
                    article.galley_set.add(galley)

                obj, created = ImportedArticleGalley.objects.get_or_create(
                    article=article,
                    eprint_id=document["eprintid"],
                    version=document["rev_number"],
                    uri=file_data["uri"],
                )
                if created:
                    self.stdout.write("Imported galley: %s " % obj)
Example #22
0
def add_pdf_galley(pdf_file, article):
    if article.pdfs:
        return

    saved_file = files.save_file_to_article(
            pdf_file, article,
            owner=None,
            label="PDF",
            is_galley=True,
    )
    galley = Galley.objects.create(
            article=article,
            file=saved_file,
            type="pdf",
            label="pdf",
    )
    article.galley_set.add(galley)
Example #23
0
def set_article_image(request, article):
    from core import logic as core_logic

    if 'delete_image' in request.POST:
        delete_id = request.POST.get('delete_image')
        file_to_delete = get_object_or_404(core_models.File,
                                           pk=delete_id,
                                           article_id=article.pk)

        if file_to_delete == article.large_image_file and request.user.is_staff or request.user == file_to_delete.owner:
            file_to_delete.delete()

        article.fixedpubcheckitems.select_article_image = False
        article.fixedpubcheckitems.save()

    if request.POST and request.FILES:
        uploaded_file = request.FILES.get('image_file')

        if not article.large_image_file:
            new_file = files.save_file_to_article(uploaded_file, article,
                                                  request.user)
            new_file.label = 'Banner image'
            new_file.description = 'Banner image'
            new_file.privacy = 'public'
            new_file.save()

            article.large_image_file = new_file
            article.save()
            messages.add_message(request, messages.SUCCESS, 'New file loaded')
        else:
            new_file = files.overwrite_file(
                uploaded_file,
                article.large_image_file,
                ('articles', article.pk),
            )
            article.large_image_file = new_file
            article.save()
            messages.add_message(request, messages.SUCCESS,
                                 'File overwritten.')

            article.fixedpubcheckitems.select_article_image = True
            article.fixedpubcheckitems.save()

        core_logic.resize_and_crop(new_file.self_article_path(), [750, 324],
                                   'middle')
Example #24
0
def save_galley_image(galley,
                      request,
                      uploaded_file,
                      label="Galley Image",
                      fixed=False):
    new_file = files.save_file_to_article(uploaded_file, galley.article,
                                          request.user)
    new_file.is_galley = False
    new_file.label = label

    if fixed:
        new_file.original_filename = request.POST.get('file_name')

    new_file.save()

    galley.images.add(new_file)

    return new_file
Example #25
0
def handle_file_post(request, copyedit):
    errors = []
    file = request.FILES.get('file')
    file_label = request.POST.get('label')

    if not file:
        errors.append('You must select a file.')
    if not file_label:
        errors.append('You must add a label for your file.')

    if not errors:
        new_file = files.save_file_to_article(file,
                                              copyedit.article,
                                              request.user,
                                              label=file_label)
        copyedit.copyeditor_files.add(new_file)
        return None
    else:
        return errors
Example #26
0
def save_galley(article, request, uploaded_file, is_galley, label, is_other):
    new_file = files.save_file_to_article(uploaded_file, article, request.user)
    new_file.is_galley = is_galley
    new_file.label = label

    if is_other:
        article.data_figure_files.add(new_file)
    else:
        article.manuscript_files.add(new_file)

    new_file.save()
    article.save()
    new_galley = core_models.Galley.objects.create(
        article=article,
        file=new_file,
        label=label,
        type=label.lower(),
        sequence=article.get_next_galley_sequence())

    return new_galley
Example #27
0
def import_copyediting(article_dict, article, client):
    copyediting = article_dict.get('copyediting', None)

    if copyediting:
        initial = copyediting.get('initial')
        author = copyediting.get('author')
        final = copyediting.get('final')

        if initial:
            email = clean_email(initial.get('email'))
            initial_copyeditor = core_models.Account.objects.get(
                email__iexact=email)
            initial_decision = True if (initial.get('underway')
                                        or initial.get('complete')) else False

            assigned = attempt_to_make_timezone_aware(initial.get('notified'))
            underway = attempt_to_make_timezone_aware(initial.get('underway'))
            complete = attempt_to_make_timezone_aware(initial.get('complete'))

            copyedit_assignment = copyediting_models\
                .CopyeditAssignment.objects.create(
                    article=article,
                    copyeditor=initial_copyeditor,
                    assigned=assigned or timezone.now(),
                    notified=True,
                    decision=initial_decision,
                    date_decided=underway if underway else complete,
                    copyeditor_completed=complete,
                    copyedit_accepted=complete
                )

            copyedit_file_url = initial.get("file")
            if copyedit_file_url:
                fetched_copyedit_file = client.fetch_file(copyedit_file_url)
                if fetched_copyedit_file:
                    copyedit_file = core_files.save_file_to_article(
                        fetched_copyedit_file,
                        article,
                        initial_copyeditor,
                        label="Copyedited File")
                    copyedit_assignment.copyeditor_files.add(copyedit_file)

            if initial and author.get('notified'):
                logger.info('Adding author review.')
                assigned = attempt_to_make_timezone_aware(
                    author.get('notified'))
                complete = attempt_to_make_timezone_aware(
                    author.get('complete'))

                author_review = copyediting_models.AuthorReview.objects.create(
                    author=article.owner,
                    assignment=copyedit_assignment,
                    assigned=assigned,
                    notified=True,
                    decision='accept',
                    date_decided=complete,
                )

                author_file_url = author.get("file")
                if author_file_url:
                    fetched_review = client.fetch_file(author_file_url)
                    if fetched_review:
                        author_review_file = core_files.save_file_to_article(
                            fetched_review,
                            article,
                            article.owner,
                            label="Author Review File",
                        )
                        author_review.files_updated.add(author_review_file)

            if final and initial_copyeditor and final.get('notified'):
                logger.info('Adding final copyedit assignment.')

                assigned = attempt_to_make_timezone_aware(
                    initial.get('notified'))
                underway = attempt_to_make_timezone_aware(
                    initial.get('underway'))
                complete = attempt_to_make_timezone_aware(
                    initial.get('complete'))

                final_decision = True if underway or complete else False

                final_assignment = copyediting_models.\
                    CopyeditAssignment.objects.create(
                        article=article,
                        copyeditor=initial_copyeditor,
                        assigned=assigned,
                        notified=True,
                        decision=final_decision,
                        date_decided=underway if underway else complete,
                        copyeditor_completed=complete,
                        copyedit_accepted=complete,
                    )
                final_file_url = final.get("file")
                if final_file_url:
                    fetched_final = client.fetch_file(final_file_url)
                    if fetched_final:
                        final_file = core_files.save_file_to_article(
                            fetched_final,
                            article,
                            initial_copyeditor,
                            label="Final File",
                        )
                        final_assignment.copyeditor_files.add(final_file)
Example #28
0
def create_article_with_review_content(article_dict, journal, auth_file,
                                       base_url):
    date_started = timezone.make_aware(
        dateparser.parse(article_dict.get('date_submitted')))

    # Create a base article
    article = models.Article(
        journal=journal,
        title=article_dict.get('title'),
        abstract=article_dict.get('abstract'),
        language=article_dict.get('language'),
        stage=models.STAGE_UNDER_REVIEW,
        is_import=True,
        date_submitted=date_started,
    )

    article.save()

    # Check for editors and assign them as section editors.
    editors = article_dict.get('editors', [])

    for editor in editors:
        try:
            account = core_models.Account.objects.get(email=editor)
            account.add_account_role('section-editor', journal)
            review_models.EditorAssignment.objects.create(
                article=article, editor=account, editor_type='section-editor')
            logger.info('Editor added to article')
        except Exception as e:
            logger.error('Editor account was not found.')
            logger.exception(e)

    # Add a new review round
    round = review_models.ReviewRound.objects.create(article=article,
                                                     round_number=1)

    # Add keywords
    keywords = article_dict.get('keywords')
    if keywords:
        for keyword in keywords.split(';'):
            word, created = models.Keyword.objects.get_or_create(word=keyword)
            article.keywords.add(word)

    # Add authors
    for author in article_dict.get('authors'):
        try:
            author_record = core_models.Account.objects.get(
                email=author.get('email'))
        except core_models.Account.DoesNotExist:
            author_record = core_models.Account.objects.create(
                email=author.get('email'),
                first_name=author.get('first_name'),
                last_name=author.get('last_name'),
                institution=author.get('affiliation'),
                biography=author.get('bio'),
            )

        # If we have a country, fetch its record
        if author.get('country'):
            try:
                country = core_models.Country.objects.get(
                    code=author.get('country'))
                author_record.country = country
                author_record.save()
            except core_models.Country.DoesNotExist:
                pass
        # Add authors to m2m and create an order record
        article.authors.add(author_record)
        models.ArticleAuthorOrder.objects.create(
            article=article,
            author=author_record,
            order=article.next_author_sort())

        # Set the primary author
        article.owner = core_models.Account.objects.get(
            email=article_dict.get('correspondence_author'))
        article.correspondence_author = article.owner

        # Get or create the article's section
        try:
            section = models.Section.objects.language().fallbacks('en').get(
                journal=journal, name=article_dict.get('section'))
        except models.Section.DoesNotExist:
            section = None

        article.section = section

        article.save()

    # Attempt to get the default review form
    form = setting_handler.get_setting('general',
                                       'default_review_form',
                                       journal,
                                       create=True).processed_value

    if not form:
        try:
            form = review_models.ReviewForm.objects.filter(journal=journal)[0]
        except Exception:
            form = None
            logger.error(
                'You must have at least one review form for the journal before'
                ' importing.')
            exit()

    for review in article_dict.get('reviews'):
        try:
            reviewer = core_models.Account.objects.get(
                email=review.get('email'))
        except core_models.Account.DoesNotExist:
            reviewer = core_models.Account.objects.create(
                email=review.get('email'),
                first_name=review.get('first_name'),
                last_name=review.get('last_name'),
            )

        # Parse the dates
        date_requested = timezone.make_aware(
            dateparser.parse(review.get('date_requested')))
        date_due = timezone.make_aware(dateparser.parse(
            review.get('date_due')))
        date_complete = timezone.make_aware(
            dateparser.parse(review.get('date_complete'))) if review.get(
                'date_complete') else None
        date_confirmed = timezone.make_aware(
            dateparser.parse(review.get('date_confirmed'))) if review.get(
                'date_confirmed') else None

        # If the review was declined, setup a date declined date stamp
        review.get('declined')
        if review.get('declined') == '1':
            date_declined = date_confirmed
            date_accepted = None
            date_complete = date_confirmed
        else:
            date_accepted = date_confirmed
            date_declined = None

        new_review = review_models.ReviewAssignment.objects.create(
            article=article,
            reviewer=reviewer,
            review_round=round,
            review_type='traditional',
            visibility='double-blind',
            date_due=date_due,
            date_requested=date_requested,
            date_complete=date_complete,
            date_accepted=date_accepted,
            access_code=uuid.uuid4(),
            form=form)

        if review.get('declined') or review.get('recommendation'):
            new_review.is_complete = True

        if review.get('recommendation'):
            new_review.decision = map_review_recommendation(
                review.get('recommendation'))

        if review.get('review_file_url'):
            filename, mime = shared.fetch_file(base_url,
                                               review.get('review_file_url'),
                                               None,
                                               None,
                                               article,
                                               None,
                                               handle_images=False,
                                               auth_file=auth_file)
            extension = os.path.splitext(filename)[1]

            review_file = shared.add_file(mime,
                                          extension,
                                          'Reviewer file',
                                          reviewer,
                                          filename,
                                          article,
                                          galley=False)
            new_review.review_file = review_file

        if review.get('comments'):
            filepath = core_files.create_temp_file(review.get('comments'),
                                                   'comment.txt')
            file = open(filepath, 'r')
            comment_file = core_files.save_file_to_article(
                file,
                article,
                article.owner,
                label='Review Comments',
                save=False)

            new_review.review_file = comment_file

        new_review.save()

    # Get MS File
    ms_file = get_ojs_file(base_url, article_dict.get('manuscript_file_url'),
                           article, auth_file, 'MS File')
    article.manuscript_files.add(ms_file)

    # Get RV File
    rv_file = get_ojs_file(base_url, article_dict.get('review_file_url'),
                           article, auth_file, 'RV File')
    round.review_files.add(rv_file)

    # Get Supp Files
    if article_dict.get('supp_files'):
        for file in article_dict.get('supp_files'):
            file = get_ojs_file(base_url, file.get('url'), article, auth_file,
                                file.get('title'))
            article.data_figure_files.add(file)

    article.save()
    round.save()

    return article
Example #29
0
def submit_files(request, article_id):
    """
    Allows the submitting author to upload files and links them to the submission
    :param request: HttpRequest object
    :param article_id: Article PK
    :return: HttpResponse
    """
    article = get_object_or_404(models.Article, pk=article_id)
    form = forms.FileDetails()

    if article.current_step < 3 and not request.user.is_staff:
        return redirect(reverse('submit_authors', kwargs={'article_id': article_id}))

    error, modal = None, None

    if request.POST:

        if 'delete' in request.POST:
            file_id = request.POST.get('delete')
            file = get_object_or_404(core_models.File, pk=file_id, article_id=article.pk)
            file.delete()
            messages.add_message(request, messages.WARNING, 'File deleted')
            return redirect(reverse('submit_files', kwargs={'article_id': article_id}))

        if 'manuscript' in request.POST:
            form = forms.FileDetails(request.POST)
            uploaded_file = request.FILES.get('file')
            if logic.check_file(uploaded_file, request, form):
                if form.is_valid():
                    new_file = files.save_file_to_article(uploaded_file, article, request.user)
                    article.manuscript_files.add(new_file)
                    new_file.label = form.cleaned_data['label']
                    new_file.description = form.cleaned_data['description']
                    new_file.save()
                    return redirect(reverse('submit_files', kwargs={'article_id': article_id}))
                else:
                    modal = 'manuscript'
            else:
                modal = 'manuscript'

        if 'data' in request.POST:
            for uploaded_file in request.FILES.getlist('file'):
                form = forms.FileDetails(request.POST)
                if form.is_valid():
                    new_file = files.save_file_to_article(uploaded_file, article, request.user)
                    article.data_figure_files.add(new_file)
                    new_file.label = form.cleaned_data['label']
                    new_file.description = form.cleaned_data['description']
                    new_file.save()
                    return redirect(reverse('submit_files', kwargs={'article_id': article_id}))
                else:
                    modal = 'data'

        if 'next_step' in request.POST:
            if article.manuscript_files.all().count() >= 1:
                article.current_step = 4
                article.save()
                return redirect(reverse('submit_review', kwargs={'article_id': article_id}))
            else:
                error = "You must upload a manuscript file."

    template = "admin/submission//submit_files.html"
    context = {
        'article': article,
        'error': error,
        'form': form,
        'modal': modal,
    }

    return render(request, template, context)
Example #30
0
def import_review_data(article_dict, article, client):
    # Add a new review round
    round, _ = review_models.ReviewRound.objects.get_or_create(
        article=article,
        round_number=1,
    )
    # Check for files at review level
    file_for_review_url = article_dict.get("review_file_url")
    fetched_file_for_review = client.fetch_file(file_for_review_url)
    if fetched_file_for_review:
        file_for_review = core_files.save_file_to_article(
            fetched_file_for_review,
            article,
            article.owner,
            label="File for Peer-Review",
        )
        round.review_files.add(file_for_review)

    # Attempt to get the default review form
    form = setting_handler.get_setting(
        'general',
        'default_review_form',
        article.journal,
    ).processed_value
    if form:
        form = review_models.ReviewForm.objects.get(id=form, )

    else:
        try:
            form = review_models.ReviewForm.objects.filter(
                journal=article.journal)[0]
        except Exception:
            form = None
            logger.error(
                'You must have at least one review form for the journal before'
                ' importing.')
            raise

    # Set for avoiding duplicate review files
    for review in article_dict.get('reviews'):
        reviewer = get_or_create_account(review)

        # Parse the dates
        date_requested = timezone.make_aware(
            dateparser.parse(review.get('date_requested')))
        date_due = timezone.make_aware(dateparser.parse(
            review.get('date_due')))
        date_complete = timezone.make_aware(
            dateparser.parse(review.get('date_complete'))) if review.get(
                'date_complete') else None
        date_confirmed = timezone.make_aware(
            dateparser.parse(review.get('date_confirmed'))) if review.get(
                'date_confirmed') else None
        date_declined = None

        review.get('declined')
        if review.get('declined') == '1':
            date_accepted = None
            date_declined = date_confirmed
        else:
            date_accepted = date_confirmed

        review_defaults = dict(review_type='traditional',
                               visibility='double-blind',
                               date_due=date_due,
                               date_requested=date_requested,
                               date_complete=date_complete,
                               date_accepted=date_accepted,
                               date_declined=date_declined,
                               access_code=uuid.uuid4(),
                               form=form)
        new_review, _ = review_models.ReviewAssignment.objects.get_or_create(
            article=article,
            reviewer=reviewer,
            review_round=round,
            defaults=review_defaults,
        )

        if review.get('declined') or review.get('recommendation'):
            new_review.is_complete = True

        if review.get('recommendation'):
            new_review.decision = REVIEW_RECOMMENDATION[
                review['recommendation']]

        # Check for files at article level
        review_file_url = review.get("review_file_url")
        if review_file_url:
            fetched_review_file = client.fetch_file(review_file_url)
            if fetched_review_file:
                review_file = core_files.save_file_to_article(
                    fetched_review_file,
                    article,
                    reviewer,
                    label="Review File",
                )
                new_review.review_file = review_file

        if review.get('comments'):
            handle_review_comment(article, new_review, review.get('comments'),
                                  form)

        new_review.save()

    # Get MS File
    manuscript_file_url = article_dict.get("manuscript_file_url")
    manuscript = client.fetch_file(manuscript_file_url, "manuscript")
    if manuscript:
        ms_file = core_files.save_file_to_article(manuscript,
                                                  article,
                                                  article.owner,
                                                  label="Manuscript")
        article.manuscript_files.add(ms_file)

    # Get Supp Files
    if article_dict.get('supp_files'):
        for supp in article_dict.get('supp_files'):
            supp = client.fetch_file(supp["url"], supp["title"])
            if supp:
                ms_file = core_files.save_file_to_article(
                    supp, article, article.owner, label="Supplementary File")
                article.data_figure_files.add(ms_file)
                round.review_files.add(ms_file)

    article.save()
    round.save()

    return article