Example #1
0
    def setUp(self):
        super(TestPhoto, self).setUp()

        # fixtures
        create_photo_formats(self)

        # "fixtures" aka example photo

        # prepare image in temporary directory
        self.image_file_name = mkstemp(suffix=".jpg", prefix="ella-photo-tests-")[1]
        self.image = Image.new('RGB', (200, 100), "black")
        self.image.save(self.image_file_name, format="jpeg")

        f = open(self.image_file_name)
        file = ContentFile(f.read())
        f.close()

        self.photo = Photo(
            title = u"Example 中文 photo",
            slug = u"example-photo",
            height = 200,
            width = 100,
        )

        self.photo.image.save("bazaaah", file)
        self.photo.save()

        self.thumbnail_path = self.photo.get_thumbnail_path()
Example #2
0
def image_pre_save(sender, instance, **kwargs):
    basetitle = instance.original_filename

    try:
        p = Photo.objects.get(title=basetitle)
    except Photo.DoesNotExist:
        p = Photo(title=basetitle)

    p.image = instance.file.file
    p.save()

    fld = instance.folder

    if fld is not None and fgs.AUTOCREATE and is_gallery_folder(fld.pretty_logical_path)[0]:
        try:
            gal = get_cached_object(Gallery, slug=slug_from_folder(fld))

            if GalleryItem.objects.filter(gallery=gal, photo=p).count() == 0:
                GalleryItem.objects.create(
                    gallery=gal,
                    photo=p,
                    order=fld.file_count
                )
        except Gallery.DoesNotExist:
            pass
    def handle(self, *args, **options):

        self.process_options(options)
        self.print_debug("Options: ")
        self.print_debug(options)

        subdir = re.sub(
            '[^('+re.escape(os.sep)+')]*%[^%].*',
            '',
            photos_settings.UPLOAD_TO
            ).strip(os.sep)

        from ella.photos.models import Photo
        storage = Photo().image.storage

        extensions = self.extensions or photos_settings.TYPE_EXTENSION.values()
        self.print_info('Accepted extensions: ' +str(extensions))
        photo_extension_re = re.compile(
                '(%s)$' % ('|'.join([re.escape(ex) for ex in extensions])),
                self.extensions_ic and re.IGNORECASE or 0)

        # breadth-first search
        files = []
        nodes = [subdir]
        while nodes:
            current = nodes.pop()
            self.print_debug("Entering directory '%s'" % current)
            current_dirs, current_files = storage.listdir(current)

            if not (current_dirs or current_files):
                self.print_info("Directory '%s' is empty" % current)
            else:
                nodes += [
                        '%s%s%s' % (current, os.sep, directory)
                        for directory in current_dirs]

                for current_file in current_files:
                    f = '%s%s%s' % (current, os.sep, current_file)
                    is_image = bool(photo_extension_re.search(current_file))
                    if not is_image:
                        self.print_info("File '%s' is not image" % f)
                    if is_image or self.all:
                        files.append(f)
                        self.print_debug("Appending file '%s'" % f)

            self.print_debug("Leaving directory '%s'" % current)

        photo_files_set = set(files)
        db_files_set = set([photo.image.url for photo in Photo.objects.all()])
        self.print_summarization(photo_files_set, db_files_set)

        if self.delete:
            self.delete_files(storage, photo_files_set -db_files_set)
Example #4
0
    def handle(self, *args, **options):

        self.process_options(options)
        self.print_debug("Options: ")
        self.print_debug(options)

        subdir = re.sub(
            '[^('+re.escape(os.sep)+')]*%[^%].*',
            '',
            photos_settings.UPLOAD_TO
            ).strip(os.sep)

        from ella.photos.models import Photo
        storage = Photo().image.storage

        extensions = self.extensions or photos_settings.TYPE_EXTENSION.values()
        self.print_info('Accepted extensions: ' +str(extensions))
        photo_extension_re = re.compile(
                '(%s)$' % ('|'.join([re.escape(ex) for ex in extensions])),
                self.extensions_ic and re.IGNORECASE or 0)

        # breadth-first search
        files = []
        nodes = [subdir]
        while nodes:
            current = nodes.pop()
            self.print_debug("Entering directory '%s'" % current)
            current_dirs, current_files = storage.listdir(current)

            if not (current_dirs or current_files):
                self.print_info("Directory '%s' is empty" % current)
            else:
                nodes += [
                        '%s%s%s' % (current, os.sep, directory)
                        for directory in current_dirs]

                for current_file in current_files:
                    f = '%s%s%s' % (current, os.sep, current_file)
                    is_image = bool(photo_extension_re.search(current_file))
                    if not is_image:
                        self.print_info("File '%s' is not image" % f)
                    if is_image or self.all:
                        files.append(f)
                        self.print_debug("Appending file '%s'" % f)

            self.print_debug("Leaving directory '%s'" % current)

        photo_files_set = set(files)
        db_files_set = set([photo.image.url for photo in Photo.objects.all()])
        self.print_summarization(photo_files_set, db_files_set)

        if self.delete:
            self.delete_files(storage, photo_files_set -db_files_set)
Example #5
0
    def setUp(self):
        super(TestPhoto, self).setUp()

        # fixtures
        create_photo_formats(self)

        # "fixtures" aka example photo

        # prepare image in temporary directory
        self.image_file_name = mkstemp(suffix=".jpg", prefix="ella-photo-tests-")[1]
        self.image = Image.new('RGB', (200, 100), "black")
        self.image.save(self.image_file_name, format="jpeg")

        f = open(self.image_file_name)
        file = ContentFile(f.read())
        f.close()

        self.photo = Photo(
            title = u"Example 中文 photo",
            slug = u"example-photo",
            height = 200,
            width = 100,
        )

        self.photo.image.save("bazaaah", file)
        self.photo.save()

        self.thumbnail_path = self.photo.get_thumbnail_path()
Example #6
0
    def save(self, force_insert=False, force_update=False):
        """Overrides models.Model.save.

        - Assigns unique slugs to the items.
        - Tries to find and parse photo in summary, in case it isn't defined on the item.
        - Saves copy of item's photo on the local servers. (Feed imports only.)
        """
        if not self.slug:
            slug = slugify(self.title)
            try:
                ServerItem.objects.get(server=self.server, slug=slug)
            except ServerItem.DoesNotExist:
                pass
            else:
                base_slug = slug + '-'
                i = 0
                while True:
                    slug = base_slug + str(i)
                    i += 1
                    try:
                        ServerItem.objects.get(server=self.server, slug=slug)
                    except ServerItem.DoesNotExist:
                        break
            self.slug = slug

        # try and parse photo
        if not self.photo_url:
            img = PHOTO_REG.findall(self.summary)
            if img:
                self.photo_url = img[0]

        if self.photo_url and not self.photo and not self.server.category:
            image = urllib.urlopen(self.photo_url)
            image_raw = image.read()
            image.close()
            imported_photo = Photo()
            imported_photo.title = self.title
            imported_photo.slug = self.slug
            imported_photo.description = self.photo_url
            # Saves "imported.jpg" file, which has been created when importing item with picture
            imported_photo.save_image_file('imported.jpg', image_raw)
            imported_photo.save()
            self.photo = imported_photo

        self.summary = strip_tags(self.summary)

        super(ServerItem, self).save(force_insert, force_update)
Example #7
0
    def _set_photo(self):
        from tempfile import mkstemp
        from django.core.files.base import ContentFile
        
        image_file_name = mkstemp(suffix=".jpg", prefix="ella-feeds-tests-")[1]
        image = Image.new('RGB', (200, 100), "black")
        image.save(image_file_name, format="jpeg")

        f = open(image_file_name)
        file = ContentFile(f.read())
        f.close()

        photo = Photo(
            title = u"Example 中文 photo",
            slug = u"example-photo",
            height = 200,
            width = 100,
        )

        photo.image.save("bazaaah", file)
        photo.save()
        
        self.publishable.photo = photo
        self.publishable.save()
Example #8
0
    def _set_photo(self):
        from tempfile import mkstemp
        from django.core.files.base import ContentFile

        image_file_name = mkstemp(suffix=".jpg", prefix="ella-feeds-tests-")[1]
        image = Image.new('RGB', (200, 100), "black")
        image.save(image_file_name, format="jpeg")

        f = open(image_file_name)
        file = ContentFile(f.read())
        f.close()

        photo = Photo(
            title=u"Example 中文 photo",
            slug=u"example-photo",
            height=200,
            width=100,
        )

        photo.image.save("bazaaah", file)
        photo.save()

        self.publishable.photo = photo
        self.publishable.save()
Example #9
0
 def generate_photo(self, instance, time):
     # TODO: handle fails
     dir_name = Photo._meta.get_field_by_name(
         'image')[0].get_directory_name()
     file_name = path.join(dir_name, 'screenshot-' + instance.file.token)
     try:
         makedirs(path.join(settings.MEDIA_ROOT, dir_name))
     except OSError:
         # Directory already exists
         pass
     instance.file.create_thumb(path.join(settings.MEDIA_ROOT, file_name),
                                time=time)
     photo = Photo()
     photo.title = "%s screenshot" % instance.title
     photo.slug = slugify(photo.title)
     photo.image = file_name
     size = get_img_size(path.join(settings.MEDIA_ROOT, file_name))
     photo.width = size['width']
     photo.height = size['height']
     photo.save()
     instance.photo = photo
Example #10
0
 def generate_photo(self, instance, time):
     # TODO: handle fails
     dir_name = Photo._meta.get_field_by_name('image')[0].get_directory_name()
     file_name = path.join(dir_name, 'screenshot-' + instance.file.token)
     try:
         makedirs(path.join(settings.MEDIA_ROOT, dir_name))
     except OSError:
         # Directory already exists
         pass
     instance.file.create_thumb(path.join(settings.MEDIA_ROOT, file_name), time=time)
     photo = Photo()
     photo.title = "%s screenshot" % instance.title
     photo.slug = slugify(photo.title)
     photo.image = file_name
     size = get_img_size(path.join(settings.MEDIA_ROOT, file_name))
     photo.width = size['width']
     photo.height = size['height']
     photo.save()
     instance.photo = photo
Example #11
0
class TestPhoto(DatabaseTestCase):

    def setUp(self):
        super(TestPhoto, self).setUp()

        # fixtures
        create_photo_formats(self)

        # "fixtures" aka example photo

        # prepare image in temporary directory
        self.image_file_name = mkstemp(suffix=".jpg", prefix="ella-photo-tests-")[1]
        self.image = Image.new('RGB', (200, 100), "black")
        self.image.save(self.image_file_name, format="jpeg")

        f = open(self.image_file_name)
        file = ContentFile(f.read())
        f.close()

        self.photo = Photo(
            title = u"Example 中文 photo",
            slug = u"example-photo",
            height = 200,
            width = 100,
        )

        self.photo.image.save("bazaaah", file)
        self.photo.save()

        self.thumbnail_path = self.photo.get_thumbnail_path()

    def test_thumbnail_html_retrieval_success(self):
        #TODO: This should be in adimn, not models
        expected_html = u'<a href="%(full)s" class="thickbox" title="%(title)s"><img src="%(thumb)s" alt="%(name)s" /></a>' % {
            'full' : "%(media)sphotos/%(date)s/%(name)s.jpg" % {
                "name" : u'%s-example-photo' % self.photo.pk,
                "media" : settings.MEDIA_URL,
                "date" : strftime("%Y/%m/%d"),
            },
            'thumb' : "%(media)sphotos/%(date)s/thumb-%(name)s.jpg" % {
                "name" : u'%s-example-photo' % self.photo.pk,
                "media" : settings.MEDIA_URL,
                "date" : strftime("%Y/%m/%d"),
            },
            "title" : u"Example 中文 photo",
            'name' : u"Thumbnail Example 中文 photo",
        }
        self.assert_equals(expected_html, self.photo.thumb())

    def test_retrieving_thumbnail_url_creates_image(self):
        url = self.photo.thumb_url()
        self.assert_equals(True, self.photo.image.storage.exists(self.thumbnail_path))

    def test_thumbnail_not_retrieved_prematurely(self):
        # aka thumbnail not created because thumb_url was not called
        self.assert_equals(False, self.photo.image.storage.exists(self.thumbnail_path))

    def test_thumbnail_path_creation(self):
        self.assert_equals("photos/2008/12/31/thumb-foo.jpg", self.photo.get_thumbnail_path("photos/2008/12/31/foo.jpg"))

    def test_thumbnail_deleted(self):
        url = self.photo.thumb_url()
        self.photo.delete()

        self.assert_equals(False, self.photo.image.storage.exists(self.thumbnail_path))

    def test_thumbnail_html_for_invalid_image(self):
        # be sneaky and delete image
        self.photo.image.storage.delete(self.photo.image.path)

        # now we are not able to detect it's format, BWAHAHA
        expected_html = """<strong>%s</strong>""" % ugettext('Thumbnail not available')
        self.assert_equals(expected_html, self.photo.thumb())

    def test_thumbnail_thumburl_for_nonexisting_image(self):
        self.photo.image.storage.delete(self.photo.image.path)
        self.assert_equals(None, self.photo.thumb_url())

    def test_retrieving_formatted_photos_on_fly(self):
        formatted = self.photo.get_formated_photo("basic")
        self.assert_equals(self.photo, formatted.photo)

    def test_formattedphoto_cleared_when_image_changed(self):
        formatted = self.photo.get_formated_photo("basic")
        self.assert_equals(1, len(self.photo.formatedphoto_set.all()))

        # let us create image again
        f = open(self.image_file_name)
        file = ContentFile(f.read())
        f.close()

        self.photo.image.save("newzaaah", file)
        self.photo.save()

        self.assert_equals(0, len(self.photo.formatedphoto_set.all()))

    def test_formattedphoto_is_none_when_image_destroyed(self):
        # be sneaky and delete image
        self.photo.image.storage.delete(self.photo.image.path)
        self.assert_equals(None, self.photo.get_formated_photo("basic"))

    def test_retrieving_ratio(self):
        self.assert_equals(2, self.photo.ratio())

    def tearDown(self):
        os.remove(self.image_file_name)
        if self.photo.pk:
            self.photo.delete()
        super(TestPhoto, self).tearDown()
Example #12
0
class TestPhoto(DatabaseTestCase):

    def setUp(self):
        super(TestPhoto, self).setUp()

        # fixtures
        create_photo_formats(self)

        # "fixtures" aka example photo

        # prepare image in temporary directory
        self.image_file_name = mkstemp(suffix=".jpg", prefix="ella-photo-tests-")[1]
        self.image = Image.new('RGB', (200, 100), "black")
        self.image.save(self.image_file_name, format="jpeg")

        f = open(self.image_file_name)
        file = ContentFile(f.read())
        f.close()

        self.photo = Photo(
            title = u"Example 中文 photo",
            slug = u"example-photo",
            height = 200,
            width = 100,
        )

        self.photo.image.save("bazaaah", file)
        self.photo.save()

        self.thumbnail_path = self.photo.get_thumbnail_path()

    def test_formatted_photo_has_zero_crop_box_if_smaller_than_format(self):
        format = Format.objects.create(
            name='sample',
            max_width=300,
            max_height=300,
            flexible_height=False,
            stretch=False,
            nocrop=False
        )
        format.sites.add(Site.objects.get_current())

        fp = FormatedPhoto(photo=self.photo, format=format)
        fp.generate(False)
        self.assert_equals((0,0,0,0), (fp.crop_left, fp.crop_top, fp.crop_width, fp.crop_height))



    def test_thumbnail_html_retrieval_success(self):
        #TODO: This should be in adimn, not models
        expected_html = u'<a href="%(full)s" class="js-nohashadr thickbox" title="%(title)s" target="_blank"><img src="%(thumb)s" alt="%(name)s" /></a>' % {
            'full' : "%(media)sphotos/%(date)s/%(name)s.jpg" % {
                "name" : u'%s-example-photo' % self.photo.pk,
                "media" : settings.MEDIA_URL,
                "date" : strftime("%Y/%m/%d"),
            },
            'thumb' : "%(media)sphotos/%(date)s/thumb-%(name)s.jpg" % {
                "name" : u'%s-example-photo' % self.photo.pk,
                "media" : settings.MEDIA_URL,
                "date" : strftime("%Y/%m/%d"),
            },
            "title" : u"Example 中文 photo",
            'name' : u"Thumbnail Example 中文 photo",
        }
        self.assert_equals(expected_html, self.photo.thumb())

    def test_retrieving_thumbnail_url_creates_image(self):
        url = self.photo.thumb_url()
        self.assert_equals(True, self.photo.image.storage.exists(self.thumbnail_path))

    def test_thumbnail_not_retrieved_prematurely(self):
        # aka thumbnail not created because thumb_url was not called
        self.assert_equals(False, self.photo.image.storage.exists(self.thumbnail_path))

    def test_thumbnail_path_creation(self):
        self.assert_equals("photos/2008/12/31/thumb-foo.jpg", self.photo.get_thumbnail_path("photos/2008/12/31/foo.jpg"))

    def test_thumbnail_deleted(self):
        url = self.photo.thumb_url()
        self.photo.delete()

        self.assert_equals(False, self.photo.image.storage.exists(self.thumbnail_path))

    def test_thumbnail_html_for_invalid_image(self):
        # be sneaky and delete image
        self.photo.image.storage.delete(self.photo.image.path)

        # now we are not able to detect it's format, BWAHAHA
        expected_html = """<strong>%s</strong>""" % ugettext('Thumbnail not available')
        self.assert_equals(expected_html, self.photo.thumb())

    def test_thumbnail_thumburl_for_nonexisting_image(self):
        self.photo.image.storage.delete(self.photo.image.path)
        self.assert_equals(None, self.photo.thumb_url())

    def test_retrieving_formatted_photos_on_fly(self):
        formatted = self.photo.get_formated_photo("basic")
        self.assert_equals(self.photo, formatted.photo)

    def test_formattedphoto_cleared_when_image_changed(self):
        formatted = self.photo.get_formated_photo("basic")
        self.assert_equals(1, len(self.photo.formatedphoto_set.all()))

        # let us create image again
        f = open(self.image_file_name)
        file = ContentFile(f.read())
        f.close()

        self.photo.image.save("newzaaah", file)
        self.photo.save()

        self.assert_equals(0, len(self.photo.formatedphoto_set.all()))

    def test_formattedphoto_is_none_when_image_destroyed(self):
        # be sneaky and delete image
        self.photo.image.storage.delete(self.photo.image.path)
        self.assert_equals(None, self.photo.get_formated_photo("basic"))

    def test_retrieving_ratio(self):
        self.assert_equals(2, self.photo.ratio())

    def tearDown(self):
        os.remove(self.image_file_name)
        if self.photo.pk:
            self.photo.delete()
        super(TestPhoto, self).tearDown()