Beispiel #1
0
def fix_series():
    old_series = Series.objects.filter(
        created__lte=settings.NEW_SITE_CREATION_DATE)

    no_prior_revs = old_series.exclude(
        revisions__created__lte=settings.NEW_SITE_CREATION_DATE)

    print "%d series to fix..." % no_prior_revs.count()
    for series in no_prior_revs:
        print "Fixing series %s" % series
        old = VieuxBoisSeries.objects.get(pk=series.pk)

        # Create changeset
        changeset = Changeset(indexer=ANON_USER,
                              approver=ANON_USER,
                              state=states.APPROVED,
                              change_type=CTYPES['series'],
                              migrated=True,
                              date_inferred=True)
        changeset.save()

        # Circumvent automatic field behavior.
        # all dates and times guaranteed to be valid
        mc = MigratoryChangeset.objects.get(id=changeset.id)
        mc.created = old.created
        mc.modified = old.modified
        mc.save()
        changeset = Changeset.objects.get(id=changeset.id)

        comment_text = COMMENT_TEXT + COMMENT_TEXT_FOR_ADD
        changeset.comments.create(commenter=ANON_USER,
                                  text=comment_text,
                                  old_state=states.APPROVED,
                                  new_state=states.APPROVED)
        comment = changeset.comments.all()[0]
        comment.created = changeset.created
        comment.save()

        revision = SeriesRevision(changeset=changeset,
                                  series=series,
                                  country=old.country,
                                  language=old.language,
                                  publisher=old.publisher,
                                  name=old.name,
                                  imprint=old.imprint,
                                  format=old.format,
                                  year_began=old.year_began,
                                  year_ended=old.year_ended,
                                  publication_notes=old.publication_notes,
                                  tracking_notes=old.tracking_notes,
                                  notes=old.notes,
                                  date_inferred=True)
        revision.save()

        # Circumvent automatic field behavior.
        mr = MigratorySeriesRevision.objects.get(id=revision.id)
        mr.created = changeset.created
        mr.modified = changeset.created
        mr.save()
def fix_series():
    old_series = Series.objects.filter(
      created__lte=settings.NEW_SITE_CREATION_DATE)

    no_prior_revs = old_series.exclude(
      revisions__created__lte=settings.NEW_SITE_CREATION_DATE)

    print "%d series to fix..." % no_prior_revs.count()
    for series in no_prior_revs:
        print "Fixing series %s" % series
        old = VieuxBoisSeries.objects.get(pk=series.pk)

        # Create changeset
        changeset = Changeset(indexer=ANON_USER, approver=ANON_USER,
                              state=states.APPROVED,
                              change_type=CTYPES['series'],
                              migrated=True, date_inferred=True)
        changeset.save()

        # Circumvent automatic field behavior.
        # all dates and times guaranteed to be valid
        mc = MigratoryChangeset.objects.get(id=changeset.id)
        mc.created = old.created
        mc.modified = old.modified
        mc.save()
        changeset = Changeset.objects.get(id=changeset.id)

        comment_text = COMMENT_TEXT + COMMENT_TEXT_FOR_ADD
        changeset.comments.create(commenter=ANON_USER,
                                  text=comment_text,
                                  old_state=states.APPROVED,
                                  new_state=states.APPROVED)
        comment = changeset.comments.all()[0]
        comment.created = changeset.created
        comment.save()

        revision = SeriesRevision(changeset=changeset,
                                  series=series,
                                  country=old.country,
                                  language=old.language,
                                  publisher=old.publisher,
                                  name=old.name,
                                  imprint=old.imprint,
                                  format=old.format,
                                  year_began=old.year_began,
                                  year_ended=old.year_ended,
                                  publication_notes=old.publication_notes,
                                  tracking_notes=old.tracking_notes,
                                  notes=old.notes,
                                  date_inferred=True)
        revision.save()

        # Circumvent automatic field behavior.
        mr = MigratorySeriesRevision.objects.get(id=revision.id)
        mr.created = changeset.created
        mr.modified = changeset.created
        mr.save()
Beispiel #3
0
def fix_pubs():
    old_pubs = Publisher.objects.filter(
        created__lte=settings.NEW_SITE_CREATION_DATE,
        parent__isnull=True,
        is_master=True)

    no_prior_revs = old_pubs.exclude(
        revisions__created__lte=settings.NEW_SITE_CREATION_DATE)

    print "%d publishers to fix..." % no_prior_revs.count()
    for pub in no_prior_revs:
        print "Fixing publisher %s" % pub
        old = VieuxBoisPublisher.objects.get(pk=pub.pk)

        # Create changeset
        changeset = Changeset(indexer=ANON_USER,
                              approver=ANON_USER,
                              state=states.APPROVED,
                              change_type=CTYPES['publisher'],
                              migrated=True,
                              date_inferred=True)
        changeset.save()

        # Circumvent automatic field behavior.
        # all dates and times guaranteed to be valid
        mc = MigratoryChangeset.objects.get(id=changeset.id)
        mc.created = old.created
        mc.modified = old.modified
        mc.save()
        changeset = Changeset.objects.get(id=changeset.id)

        comment_text = COMMENT_TEXT + COMMENT_TEXT_FOR_ADD
        changeset.comments.create(commenter=ANON_USER,
                                  text=comment_text,
                                  old_state=states.APPROVED,
                                  new_state=states.APPROVED)
        comment = changeset.comments.all()[0]
        comment.created = changeset.created
        comment.save()

        revision = PublisherRevision(changeset=changeset,
                                     publisher=pub,
                                     country=old.country,
                                     is_master=old.is_master,
                                     name=old.name,
                                     year_began=old.year_began,
                                     year_ended=old.year_ended,
                                     notes=old.notes,
                                     url=old.url,
                                     date_inferred=True)
        revision.save()

        # Circumvent automatic field behavior.
        mr = MigratoryPublisherRevision.objects.get(id=revision.id)
        mr.created = changeset.created
        mr.modified = changeset.created
        mr.save()
Beispiel #4
0
def any_variant_adding_changeset(any_indexer):
    """
    Use this when adding a variant.
    """
    # TODO: A better strategy for dealing with changesets in fixtures.
    c = Changeset(state=states.OPEN,
                  indexer=any_indexer,
                  change_type=CTYPES['variant_add'])
    c.save()
    return c
def any_variant_adding_changeset(any_indexer):
    """
    Use this when adding a varaint.
    """
    # TODO: A better strategy for dealing with changesets in fixtures.
    c = Changeset(state=states.OPEN,
                  indexer=any_indexer,
                  change_type=CTYPES['variant_add'])
    c.save()
    return c
def any_deleting_changeset(any_indexer):
    """
    Use this when deleting an already-added object.
    """
    # TODO: A better strategy for dealing with changesets in fixtures.
    c = Changeset(state=states.OPEN,
                  indexer=any_indexer,
                  change_type=CTYPES['publisher'])  # CTYPE is arbitrary
    c.save()
    return c
Beispiel #7
0
def any_deleting_changeset(any_indexer):
    """
    Use this when deleting an already-added object.
    """
    # TODO: A better strategy for dealing with changesets in fixtures.
    c = Changeset(state=states.OPEN,
                  indexer=any_indexer,
                  change_type=CTYPES['publisher'])  # CTYPE is arbitrary
    c.save()
    return c
def any_changeset(any_indexer):
    """
    Use this when the state of the changeset is irrelevant.
    """
    # TODO: A better strategy for dealing with changesets in fixtures.
    c = Changeset(state=states.OPEN,
                  indexer=any_indexer,
                  change_type=CTYPES['publisher'])
    c.save()
    return c
Beispiel #9
0
def patched_edit(story_revs):
    with mock.patch(RECENT) as recent_mock, mock.patch(SAVE), \
            mock.patch('%s.storyrevisions' % CSET) as story_mock:
        story_mock.filter.return_value = story_revs
        ish = Issue(is_indexed=INDEXED['full'])
        prev = IssueRevision(changeset=Changeset(), issue=ish)
        rev = IssueRevision(changeset=Changeset(),
                            previous_revision=prev,
                            issue=ish)
        yield (rev, recent_mock)
Beispiel #10
0
def any_changeset(any_indexer):
    """
    Use this when the state of the changeset is irrelevant.
    """
    # TODO: A better strategy for dealing with changesets in fixtures.
    c = Changeset(state=states.OPEN,
                  indexer=any_indexer,
                  change_type=CTYPES['publisher'])
    c.save()
    return c
Beispiel #11
0
def pre_commit_rev():
    with mock.patch('%s._same_series_revisions' % IREV), \
            mock.patch('%s._same_series_open_with_after' % IREV):
        s = Series(name='Some Series')
        i = Issue(number='1', series=s)
        rev = IssueRevision(
            changeset=Changeset(),
            issue=i,
            series=s,
            previous_revision=IssueRevision(changeset=Changeset(), issue=i))
        yield rev
def fix_pubs():
    old_pubs = Publisher.objects.filter(
      created__lte=settings.NEW_SITE_CREATION_DATE,
      parent__isnull=True, is_master=True)

    no_prior_revs = old_pubs.exclude(
      revisions__created__lte=settings.NEW_SITE_CREATION_DATE)

    print "%d publishers to fix..." % no_prior_revs.count()
    for pub in no_prior_revs:
        print "Fixing publisher %s" % pub
        old = VieuxBoisPublisher.objects.get(pk=pub.pk)

        # Create changeset
        changeset = Changeset(indexer=ANON_USER, approver=ANON_USER,
                              state=states.APPROVED,
                              change_type=CTYPES['publisher'],
                              migrated=True, date_inferred=True)
        changeset.save()

        # Circumvent automatic field behavior.
        # all dates and times guaranteed to be valid
        mc = MigratoryChangeset.objects.get(id=changeset.id)
        mc.created = old.created
        mc.modified = old.modified
        mc.save()
        changeset = Changeset.objects.get(id=changeset.id)

        comment_text = COMMENT_TEXT + COMMENT_TEXT_FOR_ADD
        changeset.comments.create(commenter=ANON_USER,
                                  text=comment_text,
                                  old_state=states.APPROVED,
                                  new_state=states.APPROVED)
        comment = changeset.comments.all()[0]
        comment.created = changeset.created
        comment.save()

        revision = PublisherRevision(changeset=changeset,
                                     publisher=pub,
                                     country=old.country,
                                     is_master=old.is_master,
                                     name=old.name,
                                     year_began=old.year_began,
                                     year_ended=old.year_ended,
                                     notes=old.notes,
                                     url=old.url,
                                     date_inferred=True)
        revision.save()

        # Circumvent automatic field behavior.
        mr = MigratoryPublisherRevision.objects.get(id=revision.id)
        mr.created = changeset.created
        mr.modified = changeset.created
        mr.save()
Beispiel #13
0
def handle_uploaded_image(request,
                          display_obj,
                          model_name,
                          image_type,
                          current_image=None):
    ''' process the uploaded file and generate ImageRevision '''

    try:
        form = UploadImageForm(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_image_upload_form(request, form, display_obj,
                                          model_name, image_type)

    # process form
    image = form.cleaned_data['image']

    if current_image:
        revision_lock = _get_revision_lock(current_image)
        if not revision_lock:
            return render_error(
                request, 'Cannot replace %s as it is already reserved.' %
                current_image.description())

    # create OI records
    changeset = Changeset(indexer=request.user,
                          state=states.OPEN,
                          change_type=CTYPES['image'])
    changeset.save()
    if current_image:
        revision_lock.changeset = changeset
        revision_lock.save()

    revision = ImageRevision(
        changeset=changeset,
        content_type=ContentType.objects.get_for_model(display_obj),
        object_id=display_obj.id,
        type=ImageType.objects.get(name=image_type),
        marked=form.cleaned_data['marked'])
    if current_image:
        revision.image = current_image
        revision.is_replacement = True
        revision.previous_revision = current_image.revisions.get(
            next_revision=None,
            changeset__state=states.APPROVED,
            committed=True)
    revision.save()
    revision.image_file.save(str(revision.id) + '.jpg', content=File(image))
    revision.changeset.submit(form.cleaned_data['comments'])
    return HttpResponseRedirect(urlresolvers.reverse('editing'))
def handle_uploaded_image(request, display_obj, model_name, image_type,
                          current_image=None):
    ''' process the uploaded file and generate ImageRevision '''

    try:
        form = UploadImageForm(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_image_upload_form(request, form, display_obj,
                                          model_name, image_type)

    # process form
    image = form.cleaned_data['image']

    if current_image:
        revision_lock = _get_revision_lock(current_image)
        if not revision_lock:
            return render_error(
              request,
              u'Cannot replace %s as it is already reserved.' %
              current_image.description())

    # create OI records
    changeset = Changeset(indexer=request.user, state=states.OPEN,
                          change_type=CTYPES['image'])
    changeset.save()
    if current_image:
        revision_lock.changeset = changeset
        revision_lock.save()

    revision = ImageRevision(
      changeset=changeset,
      content_type=ContentType.objects.get_for_model(display_obj),
      object_id=display_obj.id, type=ImageType.objects.get(name=image_type),
      marked=form.cleaned_data['marked'])
    if current_image:
        revision.image = current_image
        revision.is_replacement = True
        revision.previous_revision = current_image.revisions.get(
                                     next_revision=None,
                                     changeset__state=states.APPROVED,
                                     committed=True)
    revision.save()
    revision.image_file.save(str(revision.id) + '.jpg', content=File(image))
    revision.changeset.submit(form.cleaned_data['comments'])
    return HttpResponseRedirect(urlresolvers.reverse('editing'))
Beispiel #15
0
def multiple_issue_revs():
    with mock.patch('apps.oi.models.Issue.objects') as obj_mock, \
            mock.patch('%s._same_series_revisions' % IREV) as same_mock, \
            mock.patch('%s._same_series_open_with_after' % IREV) as after_mock:

        same_mock.return_value.filter.return_value.exists.return_value = False

        s = Series(name='Some Series')
        # Issues already created, so they have sort codes.
        i1 = Issue(number='1', series=s, sort_code=0)
        i4 = Issue(number='4', series=s, sort_code=1)
        i5 = Issue(number='5', series=s, sort_code=2)
        i1.save = mock.MagicMock()
        i4.save = mock.MagicMock()
        i5.save = mock.MagicMock()

        # Issues being created, no sort codes yet.
        i2 = Issue(number='2', series=s)
        i3 = Issue(number='3', series=s)

        c = Changeset()
        rev2 = IssueRevision(changeset=c, issue=i2, series=s,
                             revision_sort_code=1)
        rev3 = IssueRevision(changeset=c, issue=i3, series=s,
                             revision_sort_code=2)

        yield ((i1, i2, i3, i4, i5), (rev2, rev3),
               after_mock, obj_mock, same_mock)
Beispiel #16
0
def test_handle_dependents_to_singleton(year_began, key_date):
    with mock.patch('%s.save' % IREV) as save_mock, \
            mock.patch('%s.commit_to_display' % IREV) as commit_mock:
        # Make the IssueRevision that would be returned by the patched
        # constructor call.  Only patch the methods for this.
        s = Series()
        c = Changeset()
        ir_params = {
            'changeset': c,
            'series': s,
            'after': None,
            'number': '[nn]',
            'publication_date': year_began,
        }
        ir = IssueRevision(**ir_params)

        with mock.patch(IREV) as ir_class_mock:
            # Now patch the IssueRevision constructor itself.
            ir_class_mock.return_value = ir
            sr = SeriesRevision(changeset=c,
                                series=s,
                                is_singleton=True,
                                year_began=year_began)

            sr._handle_dependents({'to is_singleton': True})

            ir_class_mock.assert_called_once_with(**ir_params)
            assert ir.key_date == key_date
            save_mock.assert_called_once_with()
            assert not commit_mock.called
def any_adding_changeset(any_indexer):
    """
    Use this when adding new objects, and close when they are added.

    Can be used for multiple object adds as long as by the time the
    test cares about the state, all adds have been committed.  This
    is because each bit of code adding objects should assume that it
    can close the changeset once those objects are added, which means
    that there will be a period where the changeset is closed but
    additional objects still need to be committed.
    """
    # TODO: A better strategy for dealing with changesets in fixtures.
    c = Changeset(state=states.OPEN,
                  indexer=any_indexer,
                  change_type=CTYPES['publisher'])  # CTYPE is arbitrary
    c.save()
    return c
Beispiel #18
0
def any_adding_changeset(any_indexer):
    """
    Use this when adding new objects, and close when they are added.

    Can be used for multiple object adds as long as by the time the
    test cares about the state, all adds have been committed.  This
    is because each bit of code adding objects should assume that it
    can close the changeset once those objects are added, which means
    that there will be a period where the changeset is closed but
    additional objects still need to be committed.
    """
    # TODO: A better strategy for dealing with changesets in fixtures.
    c = Changeset(state=states.OPEN,
                  indexer=any_indexer,
                  change_type=CTYPES['publisher'])  # CTYPE is arbitrary
    c.save()
    return c
Beispiel #19
0
def test_same_series_revisions():
    with mock.patch('%s.issuerevisions' % CSET) as irevs_mock:
        series = Series()
        ss_revs = mock.MagicMock()
        irevs_mock.filter.return_value = ss_revs
        rev = IssueRevision(changeset=Changeset(), series=series)

        assert rev._same_series_revisions() == ss_revs
        irevs_mock.filter.assert_called_once_with(series=series)
Beispiel #20
0
def test_handle_prerequisites_deleted_singleton():
    ir_mock = mock.MagicMock()
    with mock.patch('%s.clone' % IREV,
                    return_value=ir_mock,
                    spec=IssueRevision), \
            mock.patch('%s.series' % SREV), \
            mock.patch('%s.save' % SREV), \
            mock.patch('%s.commit_to_display' % SREV):
        s = SeriesRevision(changeset=Changeset(),
                           previous_revision=SeriesRevision())
        s.deleted = True
        s.series.is_singleton = True
Beispiel #21
0
def test_handle_dependents_add(story_revs):
    with mock.patch(SAVE), \
            mock.patch('%s.storyrevisions' % CSET) as story_mock:
        story_mock.filter.return_value = story_revs
        rev = IssueRevision(changeset=Changeset(),
                            issue=Issue(is_indexed=INDEXED['full']))

        rev._handle_dependents({})

        for story in story_revs:
            assert story.issue == rev.issue
            story.save.assert_called_once_with()
Beispiel #22
0
def test_post_save_no_series_changed(patch_for_optional_move):
    patch_for_optional_move.return_value = False

    s = Series(name="Test Series")
    i = Issue(series=s)
    rev = IssueRevision(changeset=Changeset(),
                        issue=i,
                        series=s,
                        previous_revision=IssueRevision(issue=i, series=s))

    rev._post_save_object({})

    # If we fail the check, there will be two calls here instead of one.
    s.set_first_last_issues.assert_called_once_with()
Beispiel #23
0
def test_clone_parameter_passthrough():
    with mock.patch('apps.oi.models.Revision._pre_initial_save',
                    return_value={}), \
            mock.patch('apps.oi.models.Revision._post_m2m_add',
                       return_value={}), \
            mock.patch('apps.oi.models.Revision.changeset'), \
            mock.patch('apps.oi.models.Revision.save'):
        exclude = {'whatever'}
        data_object = mock.MagicMock()
        data_object.keywords.all.return_value.order_by.return_value = {}
        rev = OtherDummyRevision.clone(data_object=data_object,
                                       changeset=Changeset(),
                                       fork=True,
                                       exclude=exclude)
        rev._pre_initial_save.assert_called_once_with(fork=True,
                                                      fork_source=data_object,
                                                      exclude=exclude)
        rev._post_m2m_add.assert_called_once_with(fork=True,
                                                  fork_source=data_object,
                                                  exclude=exclude)
Beispiel #24
0
def patched_for_commit(patched_for_save):
    # We don't actually need save patched, but it's harmless and easy.
    save_mock, origin, target = patched_for_save

    with mock.patch('apps.oi.models.StoryRevision.commit_to_display'), \
            mock.patch('apps.oi.models.StoryRevision.refresh_from_db'), \
            mock.patch('apps.oi.models.Revision.open',
                       new_callable=mock.PropertyMock) as open_mock:

        # By default, assume not open, and committed=True
        c = Changeset()
        open_mock.return_value = False
        origin_rev = StoryRevision(changeset=c, story=origin, committed=True)
        target_rev = StoryRevision(changeset=c, story=target, committed=True)

        # Need to track instance calls separately.
        origin_rev.commit_to_display = mock.MagicMock()
        target_rev.commit_to_display = mock.MagicMock()

        yield origin_rev, target_rev, open_mock
Beispiel #25
0
def patch_for_move(patch_for_optional_move):
    patch_for_optional_move.return_value = True

    old = Series(name="Old Test Series")
    new = Series(name="New Test Series")
    i = Issue(series=old)

    rev = IssueRevision(changeset=Changeset(),
                        issue=i,
                        series=new,
                        previous_revision=IssueRevision(issue=i, series=old))

    # Need to track these calls independently, so replace class-level mock
    # with instance-level mocks.
    old.save = mock.MagicMock()
    new.save = mock.MagicMock()
    old.set_first_last_issues = mock.MagicMock()
    new.set_first_last_issues = mock.MagicMock()

    yield rev, i, old, new
def test_noncomics_counts(any_added_series_rev,
                          issue_add_values,
                          any_adding_changeset,
                          any_variant_adding_changeset,
                          any_deleting_changeset):
    # This is written out in long form because while it could be broken
    # up into fixtures and separate cases, it is only this one specific
    # sequence of operations that needs any of this code right now.
    s_rev = any_added_series_rev
    s_rev.is_comics_publication = False
    s_rev.save()
    with mock.patch(UPDATE_ALL) as updater:
        s_rev.commit_to_display()

    updater.has_calls([
      mock.call({}, language=None, country=None, negate=True),
      mock.call({'series': 1}, 
                language=s_rev.series.language, country=s_rev.series.country),
    ])

    assert updater.call_count == 2

    series = Series.objects.get(pk=s_rev.series.pk)

    issue_add_values['series'] = series

    i_rev = IssueRevision(changeset=any_adding_changeset, **issue_add_values)
    i_rev.save()
    i_rev = IssueRevision.objects.get(pk=i_rev.pk)

    old_series_issue_count = i_rev.series.issue_count
    old_ind_pub_issue_count = i_rev.indicia_publisher.issue_count
    old_brand_issue_count = i_rev.brand.issue_count
    old_brand_group_counts = {group.pk: group.issue_count
                              for group in i_rev.brand.group.all()}
    old_publisher_issue_count = i_rev.series.publisher.issue_count

    with mock.patch(UPDATE_ALL) as updater:
        i_rev.commit_to_display()
    # Changeset must be approved so we can re-edit this later.
    i_rev.changeset.state = states.APPROVED
    i_rev.changeset.save()

    updater.has_calls([
      mock.call({}, language=None, country=None, negate=True),
      mock.call({'stories': 0, 'covers': 0}, 
                language=i_rev.series.language, country=i_rev.series.country),
    ])

    assert updater.call_count == 2

    i_rev = IssueRevision.objects.get(pk=i_rev.pk)
    s = i_rev.issue.series
    # Non-comics issues do not affect the issue counts EXCEPT on the series.
    assert s.issue_count == old_series_issue_count + 1
    assert s.publisher.issue_count == old_publisher_issue_count
    assert i_rev.issue.brand.issue_count == old_brand_issue_count
    assert {
        group.pk: group.issue_count for group in i_rev.issue.brand.group.all()
    } == old_brand_group_counts
    assert i_rev.issue.indicia_publisher.issue_count == old_ind_pub_issue_count

    # Now do it all again with a variant added to the new issue.
    v_rev = IssueRevision(changeset=any_variant_adding_changeset,
                          number='100',
                          variant_of=i_rev.issue,
                          variant_name='alternate cover',
                          series=i_rev.series,
                          brand=i_rev.brand,
                          indicia_publisher=i_rev.indicia_publisher)
    v_rev.save()
    v_rev = IssueRevision.objects.get(pk=v_rev.pk)

    old_series_issue_count = v_rev.series.issue_count
    old_ind_pub_issue_count = v_rev.indicia_publisher.issue_count
    old_brand_issue_count = v_rev.brand.issue_count
    old_brand_group_counts = {group.pk: group.issue_count
                              for group in v_rev.brand.group.all()}
    old_publisher_issue_count = v_rev.series.publisher.issue_count

    with mock.patch(UPDATE_ALL) as updater:
        v_rev.commit_to_display()
    # Changeset must be approved so we can re-edit this later.
    v_rev.changeset.state = states.APPROVED
    v_rev.changeset.save()

    updater.has_calls([
      mock.call({'stories': 0, 'covers': 0}, language=None, country=None,
                negate=True),
      mock.call({'stories': 0, 'covers': 0}, 
                language=i_rev.series.language, country=i_rev.series.country),
    ])

    assert updater.call_count == 2

    v_rev = IssueRevision.objects.get(pk=v_rev.pk)
    s = v_rev.issue.series
    # Non-comics variants do not affect the issue counts on anything.
    assert s.issue_count == old_series_issue_count
    assert s.publisher.issue_count == old_publisher_issue_count
    assert v_rev.issue.brand.issue_count == old_brand_issue_count
    assert {
        group.pk: group.issue_count
        for group in v_rev.issue.brand.group.all()
    } == old_brand_group_counts
    assert v_rev.issue.indicia_publisher.issue_count == old_ind_pub_issue_count

    # Now delete the variant, should still have the same counts.
    del_v_rev = IssueRevision.clone(
        changeset=any_deleting_changeset,
        data_object=Issue.objects.get(pk=v_rev.issue.pk))

    del_v_rev.deleted = True
    del_v_rev.save()
    del_v_rev = IssueRevision.objects.get(pk=del_v_rev.pk)
    with mock.patch(UPDATE_ALL) as updater:
        del_v_rev.commit_to_display()

    del_v_rev = IssueRevision.objects.get(pk=del_v_rev.pk)

    updater.has_calls([
      mock.call({'stories': 0, 'covers': 0}, language=None, country=None,
                negate=True),
      mock.call({'stories': 0, 'covers': 0}, 
                language=i_rev.series.language, country=i_rev.series.country),
    ])
    assert updater.call_count == 2

    s = Series.objects.get(pk=del_v_rev.series.pk)
    i = Issue.objects.get(pk=del_v_rev.issue.pk)
    assert s.issue_count == old_series_issue_count
    assert s.publisher.issue_count == old_publisher_issue_count
    assert i.brand.issue_count == old_brand_issue_count
    assert {group.pk: group.issue_count
            for group in i.brand.group.all()} == old_brand_group_counts
    assert i.indicia_publisher.issue_count == old_ind_pub_issue_count

    # Finally, delete the base issue, check for only series.issue_count
    deleting_variant_changeset = Changeset(
        state=states.OPEN, change_type=0,
        indexer=any_deleting_changeset.indexer)
    deleting_variant_changeset.save()
    del_i_rev = IssueRevision.clone(
        changeset=deleting_variant_changeset,
        data_object=Issue.objects.get(pk=i_rev.issue.pk))

    del_i_rev.deleted = True
    del_i_rev.save()
    del_i_rev = IssueRevision.objects.get(pk=del_i_rev.pk)

    with mock.patch(UPDATE_ALL) as updater:
        del_i_rev.commit_to_display()

    del_i_rev = IssueRevision.objects.get(pk=del_v_rev.pk)
    updater.has_calls([
      mock.call({'stories': 0, 'covers': 0}, language=None, country=None,
                negate=True),
      mock.call({'stories': 0, 'covers': 0}, 
                language=i_rev.series.language, country=i_rev.series.country),
    ])
    assert updater.call_count == 2
    s = Series.objects.get(pk=del_i_rev.series.pk)
    i = Issue.objects.get(pk=del_i_rev.issue.pk)

    # Series issue counts are adjusted even for non comics.
    assert s.issue_count == old_series_issue_count - 1
    assert s.publisher.issue_count == old_publisher_issue_count
    assert i.brand.issue_count == old_brand_issue_count
    assert {group.pk: group.issue_count
            for group in i.brand.group.all()} == old_brand_group_counts
    assert i.indicia_publisher.issue_count == old_ind_pub_issue_count
Beispiel #27
0
def test_noncomics_counts(any_added_series_rev, issue_add_values,
                          any_adding_changeset, any_variant_adding_changeset,
                          any_deleting_changeset):
    # This is written out in long form because while it could be broken
    # up into fixtures and separate cases, it is only this one specific
    # sequence of operations that needs any of this code right now.
    s_rev = any_added_series_rev
    s_rev.is_comics_publication = False
    s_rev.save()
    with mock.patch(UPDATE_ALL) as updater:
        s_rev.commit_to_display()

    updater.has_calls([
        mock.call({}, language=None, country=None, negate=True),
        mock.call({'series': 1},
                  language=s_rev.series.language,
                  country=s_rev.series.country),
    ])

    assert updater.call_count == 2

    series = Series.objects.get(pk=s_rev.series.pk)

    issue_add_values['series'] = series

    i_rev = IssueRevision(changeset=any_adding_changeset, **issue_add_values)
    i_rev.save()
    i_rev = IssueRevision.objects.get(pk=i_rev.pk)

    old_series_issue_count = i_rev.series.issue_count
    old_ind_pub_issue_count = i_rev.indicia_publisher.issue_count
    old_brand_issue_count = i_rev.brand.issue_count
    old_brand_group_counts = {
        group.pk: group.issue_count
        for group in i_rev.brand.group.all()
    }
    old_publisher_issue_count = i_rev.series.publisher.issue_count

    with mock.patch(UPDATE_ALL) as updater:
        i_rev.commit_to_display()
    # Changeset must be approved so we can re-edit this later.
    i_rev.changeset.state = states.APPROVED
    i_rev.changeset.save()

    updater.has_calls([
        mock.call({}, language=None, country=None, negate=True),
        mock.call({
            'stories': 0,
            'covers': 0
        },
                  language=i_rev.series.language,
                  country=i_rev.series.country),
    ])

    assert updater.call_count == 2

    i_rev = IssueRevision.objects.get(pk=i_rev.pk)
    s = i_rev.issue.series
    # Non-comics issues do not affect the issue counts EXCEPT on the series.
    assert s.issue_count == old_series_issue_count + 1
    assert s.publisher.issue_count == old_publisher_issue_count
    assert i_rev.issue.brand.issue_count == old_brand_issue_count
    assert {
        group.pk: group.issue_count
        for group in i_rev.issue.brand.group.all()
    } == old_brand_group_counts
    assert i_rev.issue.indicia_publisher.issue_count == old_ind_pub_issue_count

    # Now do it all again with a variant added to the new issue.
    v_rev = IssueRevision(changeset=any_variant_adding_changeset,
                          number='100',
                          variant_of=i_rev.issue,
                          variant_name='alternate cover',
                          series=i_rev.series,
                          brand=i_rev.brand,
                          indicia_publisher=i_rev.indicia_publisher)
    v_rev.save()
    v_rev = IssueRevision.objects.get(pk=v_rev.pk)

    old_series_issue_count = v_rev.series.issue_count
    old_ind_pub_issue_count = v_rev.indicia_publisher.issue_count
    old_brand_issue_count = v_rev.brand.issue_count
    old_brand_group_counts = {
        group.pk: group.issue_count
        for group in v_rev.brand.group.all()
    }
    old_publisher_issue_count = v_rev.series.publisher.issue_count

    with mock.patch(UPDATE_ALL) as updater:
        v_rev.commit_to_display()
    # Changeset must be approved so we can re-edit this later.
    v_rev.changeset.state = states.APPROVED
    v_rev.changeset.save()

    updater.has_calls([
        mock.call({
            'stories': 0,
            'covers': 0
        },
                  language=None,
                  country=None,
                  negate=True),
        mock.call({
            'stories': 0,
            'covers': 0
        },
                  language=i_rev.series.language,
                  country=i_rev.series.country),
    ])

    assert updater.call_count == 2

    v_rev = IssueRevision.objects.get(pk=v_rev.pk)
    s = v_rev.issue.series
    # Non-comics variants do not affect the issue counts on anything.
    assert s.issue_count == old_series_issue_count
    assert s.publisher.issue_count == old_publisher_issue_count
    assert v_rev.issue.brand.issue_count == old_brand_issue_count
    assert {
        group.pk: group.issue_count
        for group in v_rev.issue.brand.group.all()
    } == old_brand_group_counts
    assert v_rev.issue.indicia_publisher.issue_count == old_ind_pub_issue_count

    # Now delete the variant, should still have the same counts.
    del_v_rev = IssueRevision.clone(
        changeset=any_deleting_changeset,
        data_object=Issue.objects.get(pk=v_rev.issue.pk))

    del_v_rev.deleted = True
    del_v_rev.save()
    del_v_rev = IssueRevision.objects.get(pk=del_v_rev.pk)
    with mock.patch(UPDATE_ALL) as updater:
        del_v_rev.commit_to_display()

    del_v_rev = IssueRevision.objects.get(pk=del_v_rev.pk)

    updater.has_calls([
        mock.call({
            'stories': 0,
            'covers': 0
        },
                  language=None,
                  country=None,
                  negate=True),
        mock.call({
            'stories': 0,
            'covers': 0
        },
                  language=i_rev.series.language,
                  country=i_rev.series.country),
    ])
    assert updater.call_count == 2

    s = Series.objects.get(pk=del_v_rev.series.pk)
    i = Issue.objects.get(pk=del_v_rev.issue.pk)
    assert s.issue_count == old_series_issue_count
    assert s.publisher.issue_count == old_publisher_issue_count
    assert i.brand.issue_count == old_brand_issue_count
    assert {group.pk: group.issue_count
            for group in i.brand.group.all()} == old_brand_group_counts
    assert i.indicia_publisher.issue_count == old_ind_pub_issue_count

    # Finally, delete the base issue, check for only series.issue_count
    deleting_variant_changeset = Changeset(
        state=states.OPEN,
        change_type=0,
        indexer=any_deleting_changeset.indexer)
    deleting_variant_changeset.save()
    del_i_rev = IssueRevision.clone(
        changeset=deleting_variant_changeset,
        data_object=Issue.objects.get(pk=i_rev.issue.pk))

    del_i_rev.deleted = True
    del_i_rev.save()
    del_i_rev = IssueRevision.objects.get(pk=del_i_rev.pk)

    with mock.patch(UPDATE_ALL) as updater:
        del_i_rev.commit_to_display()

    del_i_rev = IssueRevision.objects.get(pk=del_v_rev.pk)
    updater.has_calls([
        mock.call({
            'stories': 0,
            'covers': 0
        },
                  language=None,
                  country=None,
                  negate=True),
        mock.call({
            'stories': 0,
            'covers': 0
        },
                  language=i_rev.series.language,
                  country=i_rev.series.country),
    ])
    assert updater.call_count == 2
    s = Series.objects.get(pk=del_i_rev.series.pk)
    i = Issue.objects.get(pk=del_i_rev.issue.pk)

    # Series issue counts are adjusted even for non comics.
    assert s.issue_count == old_series_issue_count - 1
    assert s.publisher.issue_count == old_publisher_issue_count
    assert i.brand.issue_count == old_brand_issue_count
    assert {group.pk: group.issue_count
            for group in i.brand.group.all()} == old_brand_group_counts
    assert i.indicia_publisher.issue_count == old_ind_pub_issue_count
def process_edited_gatefold_cover(request):
    ''' process the edited gatefold cover and generate CoverRevision '''

    if request.method != 'POST':
        return render_error(request,
            'This page may only be accessed through the proper form',
            redirect=False)

    form = GatefoldScanForm(request.POST)
    if not form.is_valid():
        error_text = 'Error: Something went wrong in the file upload.'
        return render_error(request, error_text, redirect=False)
    cd = form.cleaned_data

    tmpdir = settings.MEDIA_ROOT + LOCAL_NEW_SCANS + 'tmp'
    scan_name = cd['scan_name']
    tmp_name = os.path.join(tmpdir, scan_name)

    if 'discard' in request.POST:
        os.remove(tmp_name)
        return HttpResponseRedirect(urlresolvers.reverse('edit_covers',
                kwargs={'issue_id': cd['issue_id']} ))

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

    if cd['cover_id']:
        cover = get_object_or_404(Cover, id=cd['cover_id'])
        issue = cover.issue
        # check if there is a pending change for the cover
        revision_lock = _get_revision_lock(cover)
        if not revision_lock:
            return render_error(
              request,
              u'Cannot replace %s as it is already reserved.' %
              cover.issue)
        changeset.save()
        revision_lock.changeset = changeset
        revision_lock.save()

        revision = CoverRevision(changeset=changeset, issue=issue,
            cover=cover, file_source=cd['source'], marked=cd['marked'],
            is_replacement = True)
    # no cover_id, therefore upload a cover to an issue (first or variant)
    else:
        changeset.save()
        issue = get_object_or_404(Issue, id=cd['issue_id'])
        cover = None
        revision = CoverRevision(changeset=changeset, issue=issue,
            file_source=cd['source'], marked=cd['marked'])
    revision.save()

    scan_name = str(revision.id) + os.path.splitext(tmp_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)

    shutil.move(tmp_name, destination_name)

    im = pyImage.open(destination_name)
    revision.is_wraparound = True
    # convert from scaled to real values
    width = cd['width']
    height = cd['height']
    left = cd['left']
    top = cd['top']
    revision.front_left = left
    revision.front_right = left + width
    revision.front_top = top
    revision.front_bottom = top + height
    revision.save()
    generate_sizes(revision, im)

    return finish_cover_revision(request, revision, cd)
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)
Beispiel #30
0
def process_edited_gatefold_cover(request):
    ''' process the edited gatefold cover and generate CoverRevision '''

    if request.method != 'POST':
        return render_error(
            request,
            'This page may only be accessed through the proper form',
            redirect=False)

    form = GatefoldScanForm(request.POST)
    if not form.is_valid():
        error_text = 'Error: Something went wrong in the file upload.'
        return render_error(request, error_text, redirect=False)
    cd = form.cleaned_data

    tmpdir = settings.MEDIA_ROOT + LOCAL_NEW_SCANS + 'tmp'
    scan_name = cd['scan_name']
    tmp_name = os.path.join(tmpdir, scan_name)

    if 'discard' in request.POST:
        os.remove(tmp_name)
        return HttpResponseRedirect(
            urlresolvers.reverse('edit_covers',
                                 kwargs={'issue_id': cd['issue_id']}))

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

    if cd['cover_id']:
        cover = get_object_or_404(Cover, id=cd['cover_id'])
        issue = cover.issue
        # check if there is a pending change for the cover
        revision_lock = _get_revision_lock(cover)
        if not revision_lock:
            return render_error(
                request,
                'Cannot replace %s as it is already reserved.' % cover.issue)
        changeset.save()
        revision_lock.changeset = changeset
        revision_lock.save()

        revision = CoverRevision(changeset=changeset,
                                 issue=issue,
                                 cover=cover,
                                 file_source=cd['source'],
                                 marked=cd['marked'],
                                 is_replacement=True)
    # no cover_id, therefore upload a cover to an issue (first or variant)
    else:
        changeset.save()
        issue = get_object_or_404(Issue, id=cd['issue_id'])
        cover = None
        revision = CoverRevision(changeset=changeset,
                                 issue=issue,
                                 file_source=cd['source'],
                                 marked=cd['marked'])
    revision.save()

    scan_name = str(revision.id) + os.path.splitext(tmp_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)

    shutil.move(tmp_name, destination_name)

    im = pyImage.open(destination_name)
    revision.is_wraparound = True
    # convert from scaled to real values
    width = cd['width']
    height = cd['height']
    left = cd['left']
    top = cd['top']
    revision.front_left = left
    revision.front_right = left + width
    revision.front_top = top
    revision.front_bottom = top + height
    revision.save()
    generate_sizes(revision, im)

    return finish_cover_revision(request, revision, cd)
Beispiel #31
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)
Beispiel #32
0
def main():
    if settings.DEBUG:
        raise ValueError('This script requires that debug be set to false!')

    brands = Brand.objects.filter(group=None, deleted=False)

    ANON_USER = User.objects.get(username=settings.ANON_USER_NAME)

    # create corresponding brand_group for each brand
    for brand in brands:
        # create BrandGroup
        changeset = Changeset(indexer=ANON_USER, approver=ANON_USER,
          state=states.REVIEWING, change_type=CTYPES['brand_group'])
        changeset.save()
        changeset.comments.create(commenter=ANON_USER,
            text='This is an automatically generated change '
                'for the creation of a brand group for a brand.',
            old_state=states.REVIEWING, new_state=states.REVIEWING)

        revision = BrandGroupRevision(changeset=changeset,
            name=brand.name,
            year_began=brand.year_began,
            year_began_uncertain=brand.year_began_uncertain,
            year_ended=brand.year_ended,
            year_ended_uncertain=brand.year_ended_uncertain,
            url=brand.url, notes=brand.notes, parent=brand.parent,
            # no keywords are copied, seemingly, only few and emblem specific
            keywords='')
        revision.save()
        changeset.approve(notes='Automatically approved.')
        brand_group = changeset.brandgrouprevisions.get().brand_group

        # assign BrandGroup to Brand
        changeset = Changeset(indexer=ANON_USER,
            approver=ANON_USER, state=states.REVIEWING, change_type=CTYPES['brand'])
        changeset.save()
        changeset.comments.create(commenter=ANON_USER,
            text='This is an automatically generated change for the '
                'assignment of a brand to its created brand group.',
            old_state=states.REVIEWING, new_state=states.REVIEWING)
        brand_revision = BrandRevision.objects.clone_revision(brand=brand,
            changeset=changeset)
        brand_revision.group.add(brand_group)
        brand_revision.save()
        changeset.approve(notes='Automatically approved.')

        # create BrandUse
        changeset = Changeset(indexer=ANON_USER, approver=ANON_USER,
                                state=states.REVIEWING, change_type=CTYPES['brand_use'])
        changeset.save()
        changeset.comments.create(commenter=ANON_USER,
            text='This is an automatically generated change '
                'for the creation of a brand use for a brand.',
            old_state=states.REVIEWING, new_state=states.REVIEWING)
        use = BrandUseRevision(changeset=changeset, emblem=brand,
            publisher=brand.parent,
            year_began=brand.year_began,
            year_began_uncertain=brand.year_began_uncertain,
            year_ended=brand.year_ended,
            year_ended_uncertain=brand.year_ended_uncertain)
        use.save()
        changeset.approve(notes='Automatically approved.')
        in_use = changeset.branduserevisions.get().brand_use
        in_use.save()