# Path: app/config/cplog.py
# class CPLog():
# 
#     context = ''
# 
#     def __init__(self, context = ''):
#         self.context = context
#         self.logger = cherrypy.log
# 
#     def info(self, msg):
#         self.log(msg, severity = logging.INFO)
# 
#     def debug(self, msg):
#         self.log(msg, severity = logging.DEBUG)
# 
#     def error(self, msg):
#         self.log(msg, severity = logging.ERROR)
# 
#     def log(self, msg = '', severity = logging.INFO):
#         try:
#             self.logger.error(msg = app.latinToAscii(msg), context = self.context, severity = severity)
#         except:
#             self.logger.error(msg = msg, context = self.context, severity = severity)
# 
#     def config(self, logPath, debug = False):
# 
#         level = logging.DEBUG if debug else logging.INFO
# 
#         # Overwrite functions
#         self.logger.time = self.time
#         self.logger.error = self.logError
#         self.logger.access = self.access
# 
#         # Set screen and level
#         self.logger.screen = debug
#         self.logger.error_log.setLevel(level)
# 
#         # Create log dir
#         if not os.path.isdir(logPath):
#             os.mkdir(logPath)
# 
#         self.logger.error_file = ""
# 
#         # Create RotatingFileHandler
#         h = handlers.RotatingFileHandler(os.path.join(logPath, 'CouchPotato.log'), 'a', 500000, 4)
#         h.setLevel(level)
#         h.setFormatter(logging.Formatter('%(asctime)s %(levelname)-5.5s %(message)s', '%H:%M:%S'))
#         self.logger.error_log.addHandler(h)
# 
#     def access(self):
#         pass
# 
#     def logError(self, msg = '', context = '', severity = logging.INFO, traceback = False):
# 
#         if traceback:
#             msg += _cperror.format_exc()
# 
#         context = context if context else self.context
#         self.logger.error_log.log(severity, '[%+25.25s] %s' % (context[-25:], msg))
# 
#     def time(self):
#         now = datetime.datetime.now()
#         return ('[%02d:%02d:%02d]' % (now.hour, now.minute, now.second))
# 
# Path: app/lib/provider/subtitle/base.py
# class subtitleBase(rss):
# 
#     def alreadyDownloaded(self, movie, file, key):
#         key = self.getKey(key)
#         movieId = 0 if not movie else movie.id
# 
#         file = latinToAscii(file)
#         results = Db.query(SubtitleHistory).filter(and_(SubtitleHistory.subtitle == key, SubtitleHistory.movie == movieId, SubtitleHistory.file == file)).all()
# 
#         if cherrypy.config.get('debug'):
#             log.debug('%s already downloaded.' % results)
#             return False
#         else:
#             for h in results:
#                 h.status = u'ignored'
#                 Db.flush()
# 
#             return len(results) > 0
# 
#     def addToHistory(self, movie, file, key, data):
#         key = self.getKey(key)
#         movieId = 0 if not movie else movie.id
# 
#         new = SubtitleHistory()
#         new.movie = movieId
#         new.file = latinToAscii(file)
#         new.subtitle = key
#         new.status = u'downloaded'
#         new.data = str(data)
#         Db.add(new)
# 
#         Db.flush()
# 
#     def getKey(self, key):
#         return self.name + '-' + str(key)


from app.config.cplog import CPLog
from app.lib.provider.subtitle.base import subtitleBase
from imdb.parser.http.bsouplxml._bsoup import BeautifulSoup
from urllib2 import URLError
from zipfile import ZipFile
import cherrypy
import hashlib
import os.path
import time
import urllib
import urllib2
    def sort(self, a, b):
        if a.get('rating') > b.get('rating'):
            if a.get('hi') and not b.get('hi'):
                return 1
            if not a.get('hi') and b.get('hi'):
                return - 1

        if a.get('rating') < b.get('rating'):
            if b.get('hi') and not a.get('hi'):
                return 1
            if not b.get('hi') and a.get('hi'):
                return - 1

        return 0

    def getItems(self, data):

        results = []

        soup = BeautifulSoup(data)
        table = soup.find("table", { "class" : "filmSubtitleList" })

        try:
            for tr in table.findAll("tr"):
                item = {}

                for td in tr.findAll('td'):
                    if td.a:
                        spans = td.a.findAll('span')
                        if len(spans) == 2:

# Path: app/config/cplog.py
# class CPLog():
# 
#     context = ''
# 
#     def __init__(self, context = ''):
#         self.context = context
#         self.logger = cherrypy.log
# 
#     def info(self, msg):
#         self.log(msg, severity = logging.INFO)
# 
#     def debug(self, msg):
#         self.log(msg, severity = logging.DEBUG)
# 
#     def error(self, msg):
#         self.log(msg, severity = logging.ERROR)
# 
#     def log(self, msg = '', severity = logging.INFO):
#         try:
#             self.logger.error(msg = app.latinToAscii(msg), context = self.context, severity = severity)
#         except:
#             self.logger.error(msg = msg, context = self.context, severity = severity)
# 
#     def config(self, logPath, debug = False):
# 
#         level = logging.DEBUG if debug else logging.INFO
# 
#         # Overwrite functions
#         self.logger.time = self.time
#         self.logger.error = self.logError
#         self.logger.access = self.access
# 
#         # Set screen and level
#         self.logger.screen = debug
#         self.logger.error_log.setLevel(level)
# 
#         # Create log dir
#         if not os.path.isdir(logPath):
#             os.mkdir(logPath)
# 
#         self.logger.error_file = ""
# 
#         # Create RotatingFileHandler
#         h = handlers.RotatingFileHandler(os.path.join(logPath, 'CouchPotato.log'), 'a', 500000, 4)
#         h.setLevel(level)
#         h.setFormatter(logging.Formatter('%(asctime)s %(levelname)-5.5s %(message)s', '%H:%M:%S'))
#         self.logger.error_log.addHandler(h)
# 
#     def access(self):
#         pass
# 
#     def logError(self, msg = '', context = '', severity = logging.INFO, traceback = False):
# 
#         if traceback:
#             msg += _cperror.format_exc()
# 
#         context = context if context else self.context
#         self.logger.error_log.log(severity, '[%+25.25s] %s' % (context[-25:], msg))
# 
#     def time(self):
#         now = datetime.datetime.now()
#         return ('[%02d:%02d:%02d]' % (now.hour, now.minute, now.second))
# 
# Path: app/lib/provider/subtitle/base.py
# class subtitleBase(rss):
# 
#     def alreadyDownloaded(self, movie, file, key):
#         key = self.getKey(key)
#         movieId = 0 if not movie else movie.id
# 
#         file = latinToAscii(file)
#         results = Db.query(SubtitleHistory).filter(and_(SubtitleHistory.subtitle == key, SubtitleHistory.movie == movieId, SubtitleHistory.file == file)).all()
# 
#         if cherrypy.config.get('debug'):
#             log.debug('%s already downloaded.' % results)
#             return False
#         else:
#             for h in results:
#                 h.status = u'ignored'
#                 Db.flush()
# 
#             return len(results) > 0
# 
#     def addToHistory(self, movie, file, key, data):
#         key = self.getKey(key)
#         movieId = 0 if not movie else movie.id
# 
#         new = SubtitleHistory()
#         new.movie = movieId
#         new.file = latinToAscii(file)
#         new.subtitle = key
#         new.status = u'downloaded'
#         new.data = str(data)
#         Db.add(new)
# 
#         Db.flush()
# 
#     def getKey(self, key):
#         return self.name + '-' + str(key)


# Path: app/lib/provider/subtitle/sources/subscene.py
from app.config.cplog import CPLog
from app.lib.provider.subtitle.base import subtitleBase
from imdb.parser.http.bsouplxml._bsoup import BeautifulSoup
from urllib2 import URLError
from zipfile import ZipFile
import cherrypy
import hashlib
import os.path
import time
import urllib
import urllib2

    def sort(self, a, b):
        if a.get('rating') > b.get('rating'):
            if a.get('hi') and not b.get('hi'):
                return 1
            if not a.get('hi') and b.get('hi'):
                return - 1

        if a.get('rating') < b.get('rating'):
            if b.get('hi') and not a.get('hi'):
                return 1
            if not b.get('hi') and a.get('hi'):
                return - 1

        return 0

    def getItems(self, data):

        results = []

        soup = BeautifulSoup(data)
        table = soup.find("table", { "class" : "filmSubtitleList" })

        try:
            for tr in table.findAll("tr"):
                item = {}

                for td in tr.findAll('td'):
                    if td.a:
                        spans = td.a.findAll('span')
                        if len(spans) == 2:

                            item['id'] = int(spans[1].get('id').replace('r', ''))