Esempio n. 1
0
 def test__resize(self):
     resizer = UploadImage(db.creator.image, self._creator.image)
     medium = resizer.resize('medium')
     im = Image.open(medium)
     self.assertEqual(im.size, UploadImage.sizes['medium'])
     thumb = resizer.resize('thumb')
     im = Image.open(thumb)
     self.assertEqual(im.size, UploadImage.sizes['thumb'])
Esempio n. 2
0
 def test__resize_all(self):
     resizer = UploadImage(db.creator.image, self._creator.image)
     resizer.resize_all()
     unused_filename, original_fullname = db.creator.image.retrieve(
         self._creator.image,
         nameonly=True,
     )
     for size in ['medium', 'thumb']:
         file_name = original_fullname.replace('/original/', '/{s}/'.format(s=size))
         self.assertTrue(os.path.exists(file_name))
Esempio n. 3
0
    def test__delete_all(self):
        resizer = UploadImage(db.creator.image, self._creator.image)
        resizer.resize_all()

        self._exist(have=['original', 'medium', 'thumb'])
        resizer.delete_all()
        self._exist(have_not=['original', 'medium', 'thumb'])
        resizer.delete_all()        # Handle subsequent delete gracefully
        self._exist(have_not=['original', 'medium', 'thumb'])
Esempio n. 4
0
 def resize(self):
     """Resize images."""
     LOG.debug('{a}: {t} {i} {f} {s}'.format(
         a='Action', t='table', i='id', f='image', s='size'))
     sizes = [self.size] if self.size else UploadImage.sizes.keys()
     for field, record_id, image_name, original in self.image_generator():
         resizer = UploadImage(field, image_name)
         for size in sizes:
             action = 'Dry run' if self.dry_run else 'Resizing'
             LOG.debug('{a}: {t} {i} {f} {s}'.format(
                 a=action, t=field.table, i=record_id, f=original, s=size))
             if not self.dry_run:
                 resizer.resize(size)
                 if str(field) == 'book_page.image' and size == 'thumb':
                     set_thumb_dimensions(
                         db, record_id, resizer.dimensions(size='thumb')
                     )
Esempio n. 5
0
 def test____init__(self):
     resizer = UploadImage(db.creator.image, self._image_name)
     self.assertTrue(resizer)
     file_name, fullname = db.creator.image.retrieve(
         self._creator.image,
         nameonly=True,
     )
     self.assertEqual(self._image_name, file_name)
     self.assertEqual(resizer._images, {})
     self.assertEqual(resizer._dimensions, {})
Esempio n. 6
0
    def test__download(self):
        downloader = Downloader()
        self.assertTrue(downloader)
        env = globals()
        request = env['request']
        request.args = [self._creator.image]

        lengths = {
            # size: bytes
            'original': 23127,
            'medium': 4723,
            'thumb': 1111,
        }

        def test_http(expect_size):
            try:
                stream = downloader.download(request, db)
            except HTTP as http:
                self.assertEqual(http.status, 200)
                self.assertEqual(http.headers['Content-Type'], 'image/jpeg')
                self.assertEqual(http.headers['Content-Disposition'], 'attachment; filename="file.jpg"')
                self.assertEqual(http.headers['Content-Length'], lengths[expect_size])

        test_http('original')

        # Image not resized, should default to original
        request.vars.size = 'medium'
        test_http('original')
        request.vars.size = 'thumb'
        test_http('original')

        resizer = UploadImage(db.creator.image, self._creator.image)
        resizer.resize_all()

        request.vars.size = None
        test_http('original')
        request.vars.size = 'medium'
        test_http('medium')
        request.vars.size = 'thumb'
        test_http('thumb')
Esempio n. 7
0
 def resize(self):
     """Resize images."""
     LOG.debug('{a}: {t} {i} {f} {s}'.format(a='Action',
                                             t='table',
                                             i='id',
                                             f='image',
                                             s='size'))
     sizes = [self.size] if self.size else UploadImage.sizes.keys()
     for field, record_id, image_name, original in self.image_generator():
         resizer = UploadImage(field, image_name)
         for size in sizes:
             action = 'Dry run' if self.dry_run else 'Resizing'
             LOG.debug('{a}: {t} {i} {f} {s}'.format(a=action,
                                                     t=field.table,
                                                     i=record_id,
                                                     f=original,
                                                     s=size))
             if not self.dry_run:
                 resizer.resize(size)
                 if str(field) == 'book_page.image' and size == 'thumb':
                     set_thumb_dimensions(db, record_id,
                                          resizer.dimensions(size='thumb'))
Esempio n. 8
0
 def test__fullname(self):
     resizer = UploadImage(db.creator.image, self._creator.image)
     self.assertEqual(
         resizer.fullname(),
         '/tmp/image_resizer/original/creator.image/{u}/{i}'.format(
             u=self._uuid_key,
             i=self._creator.image,
         ),
     )
     self.assertEqual(
         resizer.fullname(size='medium'),
         '/tmp/image_resizer/medium/creator.image/{u}/{i}'.format(
             u=self._uuid_key,
             i=self._creator.image,
         ),
     )
     self.assertEqual(
         resizer.fullname(size='_fake_'),
         '/tmp/image_resizer/_fake_/creator.image/{u}/{i}'.format(
             u=self._uuid_key,
             i=self._creator.image,
         ),
     )
Esempio n. 9
0
    def test__pil_image(self):
        resizer = UploadImage(db.creator.image, self._creator.image)
        self.assertEqual(resizer._images, {})

        im = resizer.pil_image()
        self.assertTrue('original' in resizer._images)
        self.assertEqual(im, resizer._images['original'])

        # Should get from cache.
        resizer._images['original'] = '_stub_'
        im_2 = resizer.pil_image()
        self.assertEqual(im_2, resizer._images['original'])

        im_3 = resizer.pil_image(size='medium')
        self.assertTrue('medium' in resizer._images)
        self.assertEqual(im_3, None)

        medium = resizer.resize('medium')
        im_4 = resizer.pil_image(size='medium')
        self.assertEqual(im_4, resizer._images['medium'])
Esempio n. 10
0
    def test__dimensions(self):
        resizer = UploadImage(db.creator.image, self._creator.image)
        self.assertEqual(resizer._dimensions, {})

        dims = resizer.dimensions()
        self.assertTrue('original' in resizer._dimensions)
        self.assertEqual(dims, resizer._dimensions['original'])

        # Should get from cache.
        resizer._dimensions['original'] = (1, 1)
        dims_2 = resizer.dimensions()
        self.assertEqual(dims_2, (1, 1))

        dims_3 = resizer.dimensions(size='medium')
        self.assertTrue('medium' in resizer._dimensions)
        self.assertEqual(dims_3, None)

        medium = resizer.resize('medium')
        dims_4 = resizer.dimensions(size='medium')
        self.assertEqual(dims_4, (500, 500))
Esempio n. 11
0
 def onupdate(form):
     """On update callback function"""
     if form.vars.image:
         resizer = UploadImage(db.creator.image, form.vars.image)
         resizer.resize_all()
Esempio n. 12
0
 def custom_delete(oldname):
     resizer = UploadImage(db.creator.image, oldname)
     resizer.delete_all()
Esempio n. 13
0
def book_pages_handler():
    """Callback function for the jQuery-File-Upload plugin.

    request.args(0): integer, id of book.

    # Add
    request.vars.up_files: list of files representing pages to add to book.

    # Delete
    request.vars.book_page_id: integer, id of book_page to delete

    """
    def do_error(msg):
        return dumps({'files': [{'error': msg}]})

    # Verify user is legit
    creator_record = db(db.creator.auth_user_id == auth.user_id).select(
        db.creator.ALL
    ).first()
    if not creator_record:
        return do_error('Upload service unavailable.')

    book_record = None
    if request.args(0):
        query = (db.book.id == request.args(0))
        book_record = db(query).select(db.book.ALL).first()
    if not book_record or book_record.creator_id != creator_record.id:
        return do_error('Upload service unavailable.')

    if request.env.request_method == 'POST':
        # Create a book_page record for each upload.
        files = request.vars.up_files
        if not isinstance(files, list):
            files = [files]
        max_page = db.book_page.page_no.max()
        page_no = db().select(max_page)[0][max_page]
        book_page_ids = []
        for file in files:
            stored_filename = db.book_page.image.store(file, file.filename)
            page_no = page_no + 1
            page_id = db.book_page.insert(
                book_id=book_record.id,
                page_no=page_no,
                image=stored_filename,
                thumb_shrink=1,
            )
            db.commit()
            resizer = UploadImage(db.book_page.image, stored_filename)
            resizer.resize_all()
            set_thumb_dimensions(db, page_id, resizer.dimensions(size='thumb'))
            book_page_ids.append(page_id)
        # Make sure page_no values are sequential
        reorder_query = (db.book_page.book_id == book_record.id)
        reorder(db.book_page.page_no, query=reorder_query)
        return book_pages_as_json(db, book_record.id, book_page_ids=book_page_ids)
    elif request.env.request_method == 'DELETE':
        do_error('Upload unavailable')
        book_page_id = request.vars.book_page_id
        book_page = db(db.book_page.id == book_page_id).select().first()
        # retrieve real file name
        filename, _ = db.book_page.image.retrieve(
            book_page.image,
            nameonly=True,
        )
        resizer = UploadImage(db.book_page.image, book_page.image)
        resizer.delete_all()
        book_page.delete_record()
        # Make sure page_no values are sequential
        reorder_query = (db.book_page.book_id == book_record.id)
        reorder(db.book_page.page_no, query=reorder_query)
        return dumps({"files": [{filename: 'true'}]})
    else:
        # GET
        return book_pages_as_json(db, book_record.id)
Esempio n. 14
0
 def onupdate(form):
     """On update callback function"""
     if form.vars.image:
         resizer = UploadImage(db.creator.image, form.vars.image)
         resizer.resize_all()
Esempio n. 15
0
 def custom_delete(oldname):
     resizer = UploadImage(db.creator.image, oldname)
     resizer.delete_all()
Esempio n. 16
0
def book_pages_handler():
    """Callback function for the jQuery-File-Upload plugin.

    request.args(0): integer, id of book.

    # Add
    request.vars.up_files: list of files representing pages to add to book.

    # Delete
    request.vars.book_page_id: integer, id of book_page to delete

    """
    def do_error(msg):
        return dumps({'files': [{'error': msg}]})

    # Verify user is legit
    creator_record = db(db.creator.auth_user_id == auth.user_id).select(
        db.creator.ALL).first()
    if not creator_record:
        return do_error('Upload service unavailable.')

    book_record = None
    if request.args(0):
        query = (db.book.id == request.args(0))
        book_record = db(query).select(db.book.ALL).first()
    if not book_record or book_record.creator_id != creator_record.id:
        return do_error('Upload service unavailable.')

    if request.env.request_method == 'POST':
        # Create a book_page record for each upload.
        files = request.vars.up_files
        if not isinstance(files, list):
            files = [files]
        max_page = db.book_page.page_no.max()
        page_no = db().select(max_page)[0][max_page]
        book_page_ids = []
        for file in files:
            stored_filename = db.book_page.image.store(file, file.filename)
            page_no = page_no + 1
            page_id = db.book_page.insert(
                book_id=book_record.id,
                page_no=page_no,
                image=stored_filename,
                thumb_shrink=1,
            )
            db.commit()
            resizer = UploadImage(db.book_page.image, stored_filename)
            resizer.resize_all()
            set_thumb_dimensions(db, page_id, resizer.dimensions(size='thumb'))
            book_page_ids.append(page_id)
        # Make sure page_no values are sequential
        reorder_query = (db.book_page.book_id == book_record.id)
        reorder(db.book_page.page_no, query=reorder_query)
        return book_pages_as_json(db,
                                  book_record.id,
                                  book_page_ids=book_page_ids)
    elif request.env.request_method == 'DELETE':
        do_error('Upload unavailable')
        book_page_id = request.vars.book_page_id
        book_page = db(db.book_page.id == book_page_id).select().first()
        # retrieve real file name
        filename, _ = db.book_page.image.retrieve(
            book_page.image,
            nameonly=True,
        )
        resizer = UploadImage(db.book_page.image, book_page.image)
        resizer.delete_all()
        book_page.delete_record()
        # Make sure page_no values are sequential
        reorder_query = (db.book_page.book_id == book_record.id)
        reorder(db.book_page.page_no, query=reorder_query)
        return dumps({"files": [{filename: 'true'}]})
    else:
        # GET
        return book_pages_as_json(db, book_record.id)