Beispiel #1
0
def upload_variant(request, issue_id):
    """
    Handles uploading of variant covers
    """
    issue = get_object_or_404(Issue, id=issue_id)

    if issue.variant_of:
        return render_error(
            request, 'Variants can only be uploaded to the base issue.')

    # check if there is a pending issue deletion
    if IssueRevision.objects.filter(issue=issue,
                                    deleted=True,
                                    changeset__state__in=states.ACTIVE):
        revision = IssueRevision.objects.get(
            issue=issue, changeset__state__in=states.ACTIVE)
        return render_error(
            request,
            ('%s is <a href="%s">pending deletion</a>. Covers '
             'cannot be added or modified.') %
            (esc(issue),
             urlresolvers.reverse('compare',
                                  kwargs={'id': revision.changeset.id})),
            redirect=False,
            is_safe=True)

    # current request is an upload
    if request.method == 'POST':
        return handle_uploaded_cover(request, None, issue, variant=True)
    # request is a GET for the form
    else:
        if 'oi_file_source' in request.session:
            vars = {
                'source': request.session['oi_file_source'],
                'remember_source': True
            }
        else:
            vars = None
        form = UploadVariantScanForm(initial=vars)
        kwargs={'pending_variant_adds': Changeset.objects\
          .filter(issuerevisions__variant_of=issue,
                  #state__in=states.ACTIVE,
                  state__in=[states.PENDING,states.REVIEWING],
                  change_type__in=[CTYPES['issue_add'],
                                   CTYPES['variant_add']])}
        # display the form
        return _display_cover_upload_form(request,
                                          form,
                                          None,
                                          issue,
                                          variant=True,
                                          kwargs=kwargs)
Beispiel #2
0
def handle_uploaded_cover(request,
                          cover,
                          issue,
                          variant=False,
                          revision_lock=None):
    ''' process the uploaded file and generate CoverRevision '''

    try:
        if variant:
            form = UploadVariantScanForm(request.POST, request.FILES)
        else:
            form = UploadScanForm(request.POST, request.FILES)
    except IOError:  # sometimes uploads misbehave. connection dropped ?
        error_text = 'Something went wrong with the upload. ' + \
                        'Please <a href="' + request.path + '">try again</a>.'
        return render_error(request, error_text, redirect=False, is_safe=True)

    if not form.is_valid():
        return _display_cover_upload_form(request,
                                          form,
                                          cover,
                                          issue,
                                          variant=variant)

    # process form
    if form.cleaned_data['is_gatefold']:
        return handle_gatefold_cover(request, cover, issue, form)
    scan = form.cleaned_data['scan']
    file_source = form.cleaned_data['source']
    marked = form.cleaned_data['marked']

    # create OI records
    changeset = Changeset(indexer=request.user,
                          state=states.OPEN,
                          change_type=CTYPES['cover'])
    changeset.save()

    if cover:  # upload_type is 'replacement':
        revision = CoverRevision(changeset=changeset,
                                 issue=issue,
                                 cover=cover,
                                 file_source=file_source,
                                 marked=marked,
                                 is_replacement=True)
        revision_lock.changeset = changeset
        revision_lock.save()
        revision.previous_revision = cover.revisions.get(
            next_revision=None,
            changeset__state=states.APPROVED,
            committed=True)
    else:
        revision = CoverRevision(changeset=changeset,
                                 issue=issue,
                                 file_source=file_source,
                                 marked=marked)
    revision.save()

    # if uploading a variant, generate an issue_revision for
    # the variant issue and copy the values which would not change
    # TODO are these reasonable assumptions below ?
    if variant:
        current_variants = issue.variant_set.all().order_by('-sort_code')
        if current_variants:
            add_after = current_variants[0]
        else:
            add_after = issue
        issue_revision = IssueRevision(
            changeset=changeset,
            after=add_after,
            number=issue.number,
            title=issue.title,
            no_title=issue.no_title,
            volume=issue.volume,
            no_volume=issue.no_volume,
            display_volume_with_number=issue.display_volume_with_number,
            variant_of=issue,
            variant_name=form.cleaned_data['variant_name'],
            page_count=issue.page_count,
            page_count_uncertain=issue.page_count_uncertain,
            series=issue.series,
            editing=issue.editing,
            no_editing=issue.no_editing,
            reservation_requested=form.cleaned_data['reservation_requested'])
        issue_revision.save()
        if form.cleaned_data['variant_artwork']:
            story_revision = StoryRevision(
                changeset=changeset,
                type=StoryType.objects.get(name='cover'),
                no_script=True,
                pencils='?',
                inks='?',
                colors='?',
                no_letters=True,
                no_editing=True,
                sequence_number=0,
                page_count=2 if form.cleaned_data['is_wraparound'] else 1,
            )
            story_revision.save()
    # put new uploaded covers into
    # media/<LOCAL_NEW_SCANS>/<monthname>_<year>/
    # with name
    # <revision_id>_<date>_<time>.<ext>
    scan_name = str(revision.id) + os.path.splitext(scan.name)[1]
    upload_dir = settings.MEDIA_ROOT + LOCAL_NEW_SCANS + \
                   changeset.created.strftime('%B_%Y').lower()
    destination_name = os.path.join(upload_dir, scan_name)
    try:  # essentially only needed at beginning of the month
        check_cover_dir(upload_dir)
    except IOError:
        changeset.delete()
        error_text = "Problem with file storage for uploaded " + \
                        "cover, please report an error."
        return render_error(request, error_text, redirect=False)

    # write uploaded file
    destination = open(destination_name, 'wb')
    for chunk in scan.chunks():
        destination.write(chunk)
    destination.close()

    try:
        # generate different sizes we are using
        im = pyImage.open(destination.name)
        large_enough = False
        if form.cleaned_data['is_wraparound']:
            # wraparounds need to have twice the width
            if im.size[0] >= 800 and im.size[1] >= 400:
                large_enough = True
        elif min(im.size) >= 400:
            large_enough = True
        if large_enough:
            if form.cleaned_data['is_wraparound']:
                revision.is_wraparound = True
                revision.front_left = im.size[0] / 2
                revision.front_right = im.size[0]
                revision.front_bottom = im.size[1]
                revision.front_top = 0
                revision.save()
            generate_sizes(revision, im)
        else:
            changeset.delete()
            os.remove(destination.name)
            info_text = "Image is too small, only " + str(im.size) + \
                        " in size."
            return _display_cover_upload_form(request,
                                              form,
                                              cover,
                                              issue,
                                              info_text=info_text,
                                              variant=variant)
    except IOError as e:
        # just in case, django *should* have taken care of file type
        changeset.delete()
        os.remove(destination.name)
        info_text = 'Error: File \"' + scan.name + \
                    '" is not a valid picture.'
        return _display_cover_upload_form(request,
                                          form,
                                          cover,
                                          issue,
                                          info_text=info_text,
                                          variant=variant)

    # all done, we can save the state
    return finish_cover_revision(request, revision, form.cleaned_data)
def handle_uploaded_cover(request, cover, issue, variant=False,
                          revision_lock=None):
    ''' process the uploaded file and generate CoverRevision '''

    try:
        if variant:
            form = UploadVariantScanForm(request.POST, request.FILES)
        else:
            form = UploadScanForm(request.POST, request.FILES)
    except IOError: # sometimes uploads misbehave. connection dropped ?
        error_text = 'Something went wrong with the upload. ' + \
                        'Please <a href="' + request.path + '">try again</a>.'
        return render_error(request, error_text, redirect=False,
            is_safe=True)

    if not form.is_valid():
        return _display_cover_upload_form(request, form, cover, issue,
                                          variant=variant)

    # process form
    if form.cleaned_data['is_gatefold']:
        return handle_gatefold_cover(request, cover, issue, form)
    scan = form.cleaned_data['scan']
    file_source = form.cleaned_data['source']
    marked = form.cleaned_data['marked']

    # create OI records
    changeset = Changeset(indexer=request.user, state=states.OPEN,
                            change_type=CTYPES['cover'])
    changeset.save()

    if cover: # upload_type is 'replacement':
        revision = CoverRevision(changeset=changeset, issue=issue,
            cover=cover, file_source=file_source, marked=marked,
            is_replacement = True)
        revision_lock.changeset = changeset
        revision_lock.save()
        revision.previous_revision = cover.revisions.get(
                                           next_revision=None,
                                           changeset__state=states.APPROVED,
                                           committed=True)
    else:
        revision = CoverRevision(changeset=changeset, issue=issue,
            file_source=file_source, marked=marked)
    revision.save()

    # if uploading a variant, generate an issue_revision for
    # the variant issue and copy the values which would not change
    # TODO are these reasonable assumptions below ?
    if variant:
        current_variants = issue.variant_set.all().order_by('-sort_code')
        if current_variants:
            add_after = current_variants[0]
        else:
            add_after = issue
        issue_revision = IssueRevision(changeset=changeset,
          after=add_after,
          number=issue.number,
          title=issue.title,
          no_title=issue.no_title,
          volume=issue.volume,
          no_volume=issue.no_volume,
          display_volume_with_number=issue.display_volume_with_number,
          variant_of=issue,
          variant_name=form.cleaned_data['variant_name'],
          page_count=issue.page_count,
          page_count_uncertain=issue.page_count_uncertain,
          series=issue.series,
          editing=issue.editing,
          no_editing=issue.no_editing,
          reservation_requested=form.cleaned_data['reservation_requested']
          )
        issue_revision.save()
        if form.cleaned_data['variant_artwork']:
            story_revision = StoryRevision(changeset=changeset,
              type=StoryType.objects.get(name='cover'),
              no_script=True,
              pencils='?',
              inks='?',
              colors='?',
              no_letters=True,
              no_editing=True,
              sequence_number=0,
              page_count=2 if form.cleaned_data['is_wraparound'] else 1,
              )
            story_revision.save()
    # put new uploaded covers into
    # media/<LOCAL_NEW_SCANS>/<monthname>_<year>/
    # with name
    # <revision_id>_<date>_<time>.<ext>
    scan_name = str(revision.id) + os.path.splitext(scan.name)[1]
    upload_dir = settings.MEDIA_ROOT + LOCAL_NEW_SCANS + \
                   changeset.created.strftime('%B_%Y').lower()
    destination_name = os.path.join(upload_dir, scan_name)
    try: # essentially only needed at beginning of the month
        check_cover_dir(upload_dir)
    except IOError:
        changeset.delete()
        error_text = "Problem with file storage for uploaded " + \
                        "cover, please report an error."
        return render_error(request, error_text, redirect=False)

    # write uploaded file
    destination = open(destination_name, 'wb')
    for chunk in scan.chunks():
        destination.write(chunk)
    destination.close()

    try:
        # generate different sizes we are using
        im = pyImage.open(destination.name)
        large_enough = False
        if form.cleaned_data['is_wraparound']:
            # wraparounds need to have twice the width
            if im.size[0] >= 800 and im.size[1] >= 400:
                large_enough = True
        elif min(im.size) >= 400:
            large_enough = True
        if large_enough:
            if form.cleaned_data['is_wraparound']:
                revision.is_wraparound = True
                revision.front_left = im.size[0]/2
                revision.front_right = im.size[0]
                revision.front_bottom = im.size[1]
                revision.front_top = 0
                revision.save()
            generate_sizes(revision, im)
        else:
            changeset.delete()
            os.remove(destination.name)
            info_text = "Image is too small, only " + str(im.size) + \
                        " in size."
            return _display_cover_upload_form(request, form, cover, issue,
                info_text=info_text, variant=variant)
    except IOError as e:
        # just in case, django *should* have taken care of file type
        changeset.delete()
        os.remove(destination.name)
        info_text = 'Error: File \"' + scan.name + \
                    '" is not a valid picture.'
        return _display_cover_upload_form(request, form, cover, issue,
            info_text=info_text, variant=variant)

    # all done, we can save the state
    return finish_cover_revision(request, revision, form.cleaned_data)