示例#1
0
文件: covers.py 项目: jochengcd/gcd
def upload_cover(request, cover_id=None, issue_id=None):
    """
    Handles uploading of covers be it
    - first upload
    - replacement upload
    - variant upload
    """

    # this cannot actually happen
    if cover_id and issue_id:
        raise ValueError

    # if cover_id is present it is a replacement upload
    if cover_id:
        cover = get_object_or_404(Cover, id=cover_id)
        issue = cover.issue
    # no cover_id, therefore upload a cover to an issue (first or variant)
    else:
        issue = get_object_or_404(Issue, id=issue_id)
        cover = None

    # 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)

    # check if there is a pending change for the cover
    if cover_id and CoverRevision.objects.filter(cover=cover,
                    changeset__state__in=states.ACTIVE):
        revision = CoverRevision.objects.get(cover=cover,
          changeset__state__in=states.ACTIVE)
        return render_error(request,
          ('There currently is a <a href="%s">pending replacement</a> '
          'for this cover of %s.') % (urlresolvers.reverse('compare',
          kwargs={'id': revision.changeset.id}), esc(cover.issue)),
          redirect=False, is_safe=True)

    # current request is an upload
    if request.method == 'POST':
        return handle_uploaded_cover(request, cover, issue)
    # 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 = UploadScanForm(initial=vars)

        # display the form
        return _display_cover_upload_form(request, form, cover, issue)
示例#2
0
def upload_cover(request, cover_id=None, issue_id=None):
    """
    Handles uploading of covers be it
    - first upload
    - replacement upload
    - variant upload
    """

    # this cannot actually happen
    if cover_id and issue_id:
        raise ValueError

    upload_template = 'oi/edit/upload_cover.html'
    style = 'default'

    # set cover, issue, covers, replace_cover, upload_type
    covers = []
    replace_cover = None
    # if cover_id is present it is a replacement upload
    if cover_id:
        cover = get_object_or_404(Cover, id=cover_id)
        issue = cover.issue

        # check if there is a pending change for the cover
        if CoverRevision.objects.filter(cover=cover,
                                        changeset__state__in=states.ACTIVE):
            revision = CoverRevision.objects.get(
                cover=cover, changeset__state__in=states.ACTIVE)
            return render_error(
                request,
                ('There currently is a <a href="%s">pending replacement</a> '
                 'for this cover of %s.') % (urlresolvers.reverse(
                     'compare', kwargs={'id': revision.changeset.id
                                        }), esc(cover.issue)),
                redirect=False,
                is_safe=True)

        upload_type = 'replacement'
        replace_cover = get_image_tag(cover, "cover to replace", ZOOM_MEDIUM)
    # no cover_id, therefore upload a cover to an issue (first or variant)
    else:
        issue = get_object_or_404(Issue, id=issue_id)
        cover = None
        if issue.has_covers():
            covers = get_image_tags_per_issue(issue,
                                              "current covers",
                                              ZOOM_MEDIUM,
                                              as_list=True)
            upload_type = 'variant'
        else:
            upload_type = ''

    # generate tags for cover uploads for this issue currently in the queue
    active_covers_tags = []
    active_covers = CoverRevision.objects.filter(
        issue=issue, changeset__state__in=states.ACTIVE,
        deleted=False).order_by('created')
    for active_cover in active_covers:
        active_covers_tags.append([
            active_cover,
            get_preview_image_tag(active_cover, "pending cover", ZOOM_MEDIUM)
        ])

    # current request is an upload
    if request.method == 'POST':
        try:
            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 render_to_response(upload_template, {
                'form': form,
                'cover': cover,
                'issue': issue,
                'style': style,
                'replace_cover': replace_cover,
                'current_covers': covers,
                'upload_type': upload_type,
                'table_width': UPLOAD_WIDTH
            },
                                      context_instance=RequestContext(request))
        # if scan is actually in the form handle it
        if 'scan' in request.FILES:
            # process form
            scan = request.FILES['scan']
            file_source = request.POST['source']
            marked = 'marked' in request.POST

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

            if upload_type == 'replacement':
                revision = CoverRevision(changeset=changeset,
                                         issue=issue,
                                         cover=cover,
                                         file_source=file_source,
                                         marked=marked,
                                         is_replacement=True)
            else:
                revision = CoverRevision(changeset=changeset,
                                         issue=issue,
                                         file_source=file_source,
                                         marked=marked)
            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 = 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 = Image.open(destination.name)
                if im.size[0] >= 400:
                    generate_sizes(revision, im)
                else:
                    changeset.delete()
                    os.remove(destination.name)
                    info_text = "Image is too small, only " + str(im.size) + \
                                " in size."
                    return render_to_response(
                        upload_template, {
                            'form': form,
                            'info': info_text,
                            'cover': cover,
                            'current_covers': covers,
                            'replace_cover': replace_cover,
                            'upload_type': upload_type,
                            'table_width': UPLOAD_WIDTH,
                            'issue': issue
                        },
                        context_instance=RequestContext(request))
            except IOError:
                # just in case, django *should* have taken care of file type
                changeset.delete()
                os.remove(destination.name)
                return render_to_response(upload_template, {
                  'form': form,
                  'info' : 'Error: File \"' + scan.name + \
                           '" is not a valid picture.',
                  'cover' : cover,
                  'issue' : issue,
                  'current_covers' : covers,
                  'replace_cover' : replace_cover,
                  'upload_type' : upload_type,
                  'table_width': UPLOAD_WIDTH
                  },
                  context_instance=RequestContext(request))

            # all done, we can save the state
            changeset.comments.create(commenter=request.user,
                                      text=form.cleaned_data['comments'],
                                      old_state=states.UNRESERVED,
                                      new_state=changeset.state)

            if 'remember_source' in request.POST:
                request.session['oi_file_source'] = request.POST['source']
            else:
                request.session.pop('oi_file_source', '')

            return HttpResponseRedirect(
                urlresolvers.reverse('upload_cover_complete',
                                     kwargs={'revision_id': revision.id}))

    # 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 = UploadScanForm(initial=vars)

        # display the form
        return render_to_response(upload_template, {
            'form': form,
            'cover': cover,
            'issue': issue,
            'current_covers': covers,
            'replace_cover': replace_cover,
            'active_covers': active_covers_tags,
            'upload_type': upload_type,
            'table_width': UPLOAD_WIDTH
        },
                                  context_instance=RequestContext(request))
示例#3
0
def upload_cover(request, cover_id=None, issue_id=None):
    """
    Handles uploading of covers be it
    - first upload
    - replacement upload
    - variant upload
    """

    # this cannot actually happen
    if cover_id and issue_id:
        raise ValueError

    # if cover_id is present it is a replacement upload
    if cover_id:
        cover = get_object_or_404(Cover, id=cover_id)
        issue = cover.issue
    # no cover_id, therefore upload a cover to an issue (first or variant)
    else:
        issue = get_object_or_404(Issue, id=issue_id)
        if not issue.can_have_cover():
            return render_error(
                request,
                'No covers for non-comics publications if the issue has less'
                ' than 10% indexed comics content.',
                redirect=False)
        cover = None

    # 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)

    # check if there is a pending change for the cover
    # if POST, get a lock
    if cover_id and request.method == 'POST':
        revision_lock = _get_revision_lock(cover)
        if not revision_lock:
            return render_error(
                request,
                'Cannot replace %s as it is already reserved.' % cover.issue)
    # if GET, check for a lock
    elif cover_id and is_locked(cover):
        return render_error(
            request,
            ('There currently is a pending replacement for this cover of %s.')
            % (cover.issue),
            redirect=False,
            is_safe=True)
    else:
        revision_lock = None

    # current request is an upload
    if request.method == 'POST':
        return handle_uploaded_cover(request,
                                     cover,
                                     issue,
                                     revision_lock=revision_lock)
    # 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 = UploadScanForm(initial=vars)

        # display the form
        return _display_cover_upload_form(request, form, cover, issue)
示例#4
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 upload_cover(request, cover_id=None, issue_id=None):
    """
    Handles uploading of covers be it
    - first upload
    - replacement upload
    - variant upload
    """

    # this cannot actually happen
    if cover_id and issue_id:
        raise ValueError

    upload_template = 'oi/edit/upload_cover.html'
    style = 'default'

    # set cover, issue, covers, replace_cover, upload_type
    covers = []
    replace_cover = None
    # if cover_id is present it is a replacement upload
    if cover_id:
        cover = get_object_or_404(Cover, id=cover_id)
        issue = cover.issue
        if not cover.has_image: 
            # nothing to replace, empty cover slot, redirect to issue upload
            return HttpResponseRedirect(urlresolvers.reverse('upload_cover',
                kwargs={'issue_id': issue.id} ))


        # check if there is a pending change for the cover
        if CoverRevision.objects.filter(cover=cover, 
                                 changeset__state__in=states.ACTIVE):
            revision = CoverRevision.objects.get(cover=cover, 
                                     changeset__state__in=states.ACTIVE)
            return render_error(request,
              ('There currently is a <a href="%s">pending replacement</a> '
               'for this cover of %s.') % (urlresolvers.reverse('compare',
                kwargs={'id': revision.changeset.id}), esc(cover.issue)),
            redirect=False, is_safe=True)

        upload_type = 'replacement'
        replace_cover = get_image_tag(cover, "cover to replace", ZOOM_MEDIUM)
    # no cover_id, therefore upload a cover to an issue (first or variant)
    else: 
        issue = get_object_or_404(Issue, id=issue_id)
        cover = issue.cover_set.latest() # latest can be the empty first one
        if cover.has_image:
            covers = get_image_tags_per_issue(issue, "current covers", 
                                              ZOOM_MEDIUM, as_list=True)
            upload_type = 'variant'
        else:
            upload_type = ''

    # generate tags for cover uploads for this issue currently in the queue
    active_covers_tags = []
    active_covers = CoverRevision.objects.filter(issue=issue, 
                    changeset__state__in=states.ACTIVE).order_by('created')
    for active_cover in active_covers:
        active_covers_tags.append([active_cover, 
                                   get_preview_image_tag(active_cover, 
                                   "pending cover", ZOOM_MEDIUM)])

    # current request is an upload
    if request.method == 'POST':
        try:
            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 render_to_response(upload_template, {
                                      'form': form,
                                      'cover' : cover,
                                      'issue' : issue,
                                      'style' : style,
                                      'replace_cover' : replace_cover,
                                      'current_covers' : covers,
                                      'upload_type' : upload_type,
                                      'table_width': UPLOAD_WIDTH
                                      },
                                      context_instance=RequestContext(request))
        # if scan is actually in the form handle it
        if 'scan' in request.FILES:
            # process form
            scan = request.FILES['scan']
            file_source = request.POST['source']
            marked = 'marked' in request.POST

            # create OI records
            changeset = Changeset(indexer=request.user, state=states.PENDING)
            changeset.save()

            if upload_type == 'replacement':
                revision = CoverRevision(changeset=changeset, issue=issue,
                  cover=cover, file_source=file_source, marked=marked,
                  is_replacement = True)
            else:
                revision = CoverRevision(changeset=changeset, issue=issue,
                  file_source=file_source, marked=marked)
            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 = 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 = Image.open(destination.name)
                if im.size[0] >= 400:
                    generate_sizes(revision, im)
                else:
                    changeset.delete()
                    os.remove(destination.name)
                    info_text = "Image is too small, only " + str(im.size) + \
                                " in size."
                    return render_to_response(upload_template, {
                      'form': form,
                      'info' : info_text,
                      'cover' : cover,
                      'current_covers' : covers,
                      'replace_cover' : replace_cover,
                      'upload_type' : upload_type,
                      'table_width': UPLOAD_WIDTH,
                      'issue' : issue
                      },
                      context_instance=RequestContext(request))
            except IOError: 
                # just in case, django *should* have taken care of file type
                changeset.delete()
                os.remove(destination.name)
                return render_to_response(upload_template, {
                  'form': form,
                  'info' : 'Error: File \"' + scan.name + \
                           '" is not a valid picture.',
                  'cover' : cover,
                  'issue' : issue,
                  'current_covers' : covers,
                  'replace_cover' : replace_cover,
                  'upload_type' : upload_type,
                  'table_width': UPLOAD_WIDTH
                  },
                  context_instance=RequestContext(request))

            # all done, we can save the state
            changeset.comments.create(commenter=request.user,
                                      text=form.cleaned_data['comments'],
                                      old_state=states.UNRESERVED,
                                      new_state=changeset.state)

            if 'remember_source' in request.POST:
                request.session['oi_file_source'] = request.POST['source']
            else:
                request.session.pop('oi_file_source','')

            return HttpResponseRedirect(urlresolvers.reverse('upload_cover_complete',
                kwargs={'revision_id': revision.id} ))

    # 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 = UploadScanForm(initial=vars)

        # display the form
        return render_to_response(upload_template, {
                                  'form': form, 
                                  'cover' : cover,
                                  'issue' : issue,
                                  'current_covers' : covers,
                                  'replace_cover' : replace_cover,
                                  'active_covers' : active_covers_tags,
                                  'upload_type' : upload_type,
                                  'table_width': UPLOAD_WIDTH},
                                  context_instance=RequestContext(request))
def handle_uploaded_cover(request, cover, issue):
    ''' process the uploaded file and generate CoverRevision '''

    try:
        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)

    # 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)
    else:
        revision = CoverRevision(changeset=changeset, issue=issue,
            file_source=file_source, marked=marked)
    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 = Image.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)
    except IOError: 
        # 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)

    # all done, we can save the state
    return finish_cover_revision(request, revision, form.cleaned_data)
示例#7
0
def handle_uploaded_cover(request, cover, issue):
    ''' process the uploaded file and generate CoverRevision '''

    try:
        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)

    # 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)
    else:
        revision = CoverRevision(changeset=changeset,
                                 issue=issue,
                                 file_source=file_source,
                                 marked=marked)
    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 = Image.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)
    except IOError:
        # 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)

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