""" Tool for proxying images and resizing if needed """
import os
import hashlib
import htpc
import logging
from cherrypy.lib.static import serve_file
from urllib2 import Request, urlopen
try:
    import Image
    import ImageEnhance
    PIL = True
except ImportError:
    PIL = False

def get_image(url, height=None, width=None, opacity=100, auth=None):
    """ Load image form cache if possible, else download. Resize if needed """
    opacity = float(opacity)
    logger = logging.getLogger('htpc.proxy')

    # Create image directory if it doesnt exist
    imgdir = os.path.join(htpc.DATADIR, 'images/')
    if not os.path.exists(imgdir):
        logger.debug("Creating image directory at " + imgdir)
        os.makedirs(imgdir)

    # Create a hash of the path to use as filename
    imghash = hashlib.md5(url).hexdigest()

    # Set filename and path
    image = os.path.join(imgdir, imghash)

    # If there is no local copy of the original
    if not os.path.isfile(image):
        logger.debug("No local image found for " + image + ". Downloading")
        download_image(url, image, auth)

    # Check if resize is needed
    if (height and width) or (opacity < 100):

        if PIL:
            # Set filename for resized file
            resized = image + '_w' + width + '_h' + height + '_o' + str(opacity)

            # If there is no local resized copy
            if not os.path.isfile(resized):
                resize_image(image, height, width, opacity, resized)

            # Serve the resized file
            image = resized
        else:
            logger.error("Can't resize when PIL is missing on system!")
            if (opacity < 100):
                image = os.path.join(htpc.RUNDIR,'interfaces/default/img/fff_20.png')

    # Load file from disk
    return serve_file(path=image, content_type='image/jpeg')


def download_image(url, dest, auth=None):
    """ Download image and save to disk """
    logger = logging.getLogger('htpc.proxy')
    logger.debug("Downloading image from " + url + " to " + dest)

    request = Request(url)

    if (auth):
        request.add_header("Authorization", "Basic %s" % auth)

    with open(dest, "wb") as local_file:
        local_file.write(urlopen(request).read())


def resize_image(img, height, width, opacity, dest):
        """ Resize image, set opacity and save to disk """
        size = int(width), int(height)
        im = Image.open(img)
        im = im.resize(size, Image.ANTIALIAS)

        # Apply overlay if opacity is set
        opacity = float(opacity)
        if (opacity < 100):
            enhance = opacity / 100
            # Create white overlay image
            overlay = Image.new('RGB', size, '#FFFFFF')
            #apply overlay to resized image
            im = Image.blend(overlay, im, enhance)

        im.save(dest, 'JPEG', quality=95)
        return dest

@@ -90,16 +90,31 @@
 t htpc%0D%0A
+import imghdr%0D%0A
 import l
@@ -1842,16 +1842,52 @@
 m disk%0D%0A
+    imagetype = imghdr.what(image)%0D%0A
     retu
@@ -1936,13 +1936,21 @@
 age/
-jpeg'
+' + imagetype
 )%0D%0A%0D
@@ -2358,26 +2358,24 @@
 .read())%0D%0A%0D%0A
-%0D%0A
 def resize_i
@@ -2516,16 +2516,54 @@
 eight)%0D%0A
+        imagetype = imghdr.what(img)%0D%0A
         
@@ -2970,24 +2970,61 @@
 enhance)%0D%0A%0D%0A
+        if imagetype == 'jpeg':%0D%0A    
         im.s
@@ -3054,16 +3054,50 @@
 ty=95)%0D%0A
+        im.save(dest, imagetype)%0D%0A
         

Support proxying GIF and PNG