# Path: htpc/proxy.py
# def get_image(url, height=None, width=None, opacity=100, auth=None, headers=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, headers)
# 
#     # 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
#     imagetype = imghdr.what(image)
#     if imagetype is not None:
#         return serve_file(path=image, content_type='image/' + imagetype)


import cherrypy
import htpc
import base64
import socket
import struct
import logging
from urllib2 import quote
from jsonrpclib import Server
from sqlobject import SQLObject, SQLObjectNotFound
from sqlobject.col import StringCol, IntCol
from htpc.proxy import get_image
from cherrypy.lib.auth2 import require
        return

    @cherrypy.expose()
    @require()
    @cherrypy.tools.json_out()
    def changeserver(self, id=0):
        try:
            self.current = XbmcServers.selectBy(id=id).getOne()
            htpc.settings.set('xbmc_current_server', str(id))
            self.logger.info("Selecting XBMC server: %s", id)
            return "success"
        except SQLObjectNotFound:
            try:
                self.current = XbmcServers.select(limit=1).getOne()
                self.logger.error("Invalid server. Selecting first Available.")
                return "success"
            except SQLObjectNotFound:
                self.current = None
                self.logger.warning("No configured XBMC-Servers.")
                return "No valid servers"

    @cherrypy.expose()
    @require()
    def GetThumb(self, thumb=None, h=None, w=None, o=100):
        """ Parse thumb to get the url and send to htpc.proxy.get_image """
        url = self.url('/images/DefaultVideo.png')
        if thumb:
            url = self.url('/image/' + quote(thumb))

        self.logger.debug("Trying to fetch image via %s", url)

# Path: htpc/proxy.py
# def get_image(url, height=None, width=None, opacity=100, auth=None, headers=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, headers)
# 
#     # 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
#     imagetype = imghdr.what(image)
#     if imagetype is not None:
#         return serve_file(path=image, content_type='image/' + imagetype)


# Path: modules/xbmc.py
import cherrypy
import htpc
import base64
import socket
import struct
import logging
from urllib2 import quote
from jsonrpclib import Server
from sqlobject import SQLObject, SQLObjectNotFound
from sqlobject.col import StringCol, IntCol
from htpc.proxy import get_image
from cherrypy.lib.auth2 import require

        return

    @cherrypy.expose()
    @require()
    @cherrypy.tools.json_out()
    def changeserver(self, id=0):
        try:
            self.current = XbmcServers.selectBy(id=id).getOne()
            htpc.settings.set('xbmc_current_server', str(id))
            self.logger.info("Selecting XBMC server: %s", id)
            return "success"
        except SQLObjectNotFound:
            try:
                self.current = XbmcServers.select(limit=1).getOne()
                self.logger.error("Invalid server. Selecting first Available.")
                return "success"
            except SQLObjectNotFound:
                self.current = None
                self.logger.warning("No configured XBMC-Servers.")
                return "No valid servers"

    @cherrypy.expose()
    @require()
    def GetThumb(self, thumb=None, h=None, w=None, o=100):
        """ Parse thumb to get the url and send to htpc.proxy.get_image """
        url = self.url('/images/DefaultVideo.png')
        if thumb:
            url = self.url('/image/' + quote(thumb))

        self.logger.debug("Trying to fetch image via %s", url)

        return get_image(url, h, w, o, self.auth())