def search(filename):
    trakt = TraktAPI()
    pattern = '\/Default\/([^\/]+)\/.*,\s(\d+_\d+)\.pvr'
    match = re.search(pattern, filename)
    if match:
        title, ts = match.groups()
    else:
        plugin.log(filename)
        return False, False, False, False
    slug = False
    imdb_id = False
    response = _call('/Dvr/GetRecordedList')
    test = ts.replace('_', '')
    for r in response['ProgramList']['Programs']:
        if r['Title'] == title and test in r['FileName']:
            season = int(r['Season'])
            episode = int(r['Episode'])
            tvdb_id = r['Inetref']
            imdb_id = trakt.translate_id(tvdb_id, "tvdb", "imdb", "show")
            break
    if imdb_id:
        uri = '/shows/%s/seasons/%s/episodes/%s' % (imdb_id, season, episode)
        eps = trakt._call(uri, params={}, auth=False, cache_limit=3600)
        if eps:
            trakt_id = eps['ids']['trakt']
            return imdb_id, season, episode, trakt_id
    del trakt
    return False, False, False, False
示例#2
0
 def process_results(self, data, re_test=None):
     results = []
     if data['status'] != 'success':
         plugin.log(data)
         return []
     gc.disable()
     for result in data['result']:
         title = self.normalize(result['title'])
         if re_test:
             if re_test.search(title) is None: continue
         sourcetitle = self.normalize(result['sourcetitle'])
         hoster = result['hosterurls']
         extension = result['extension']
         size = result['sizeinternal']
         extension = result['extension']
         host_name = result['hostername']
         hosts = result['hosterurls']
         if extension == 'rar': continue
         for host in hosts:
             if self.filter_host(host_name):
                 url = "%s://%s" % (self.service, host['url'])
                 quality = self.test_quality(title + sourcetitle +
                                             self.normalize(url))
                 result = ScraperResult(self.debrid_hosts, self.service,
                                        host_name, url, title)
                 result.quality = quality
                 result.size = int(size)
                 result.extension = extension
                 results += [result]
     gc.enable()
     return results
 def get_provider(self, link):
     skey = self.strip_tags(link).lower()
     table = {
         '180upload': '180upload.com',
         'hugefiles': 'hugefiles.net',
         'clicknupload': 'clicknupload.com',
         'tusfiles': 'tusfiles.net',
         'xfileload': 'xfileload.com',
         'mightyupload': 'mightyupload.com',
         'movreel': 'movreel.com',
         'donevideo': 'donevideo.com',
         'vidplay': 'vidplay.net',
         '24uploading': '24uploading.com',
         'xvidstage': 'xvidstage.com',
         '2shared': '2shared.com',
         'upload': 'upload.af',
         'uploadx': 'uploadx.org',
         'kingfiles': 'kingfiles.net',
         'openload': 'openload.co',
         'uploadz': 'uploadz.co',
         'fileweed': 'fileweed.net',
         'filehoot': 'filehoot.com'
     }
     if skey in table.keys():
         return table[skey]
     else:
         plugin.log("Icefilms unmatched host: %s" % skey)
     return None
 def run(self, mode='default'):
     if mode is None or mode == '' or mode is False:
         mode = 'default'
     if mode in self.__functions:
         args = self.__args[mode]
         kwargs = self.__kwargs[mode]
         try:
             self.__functions[mode](*args, **kwargs)
         except Exception, e:
             log("Dispatcher Error in mode %s:  %s" % (mode, e))
             self.error()
 def _login(self):
     params = {"login": self.username, "pwd": self.password}
     uri = '/login/login'
     response = self.request(uri, params=params)
     if 'status' in response.keys():
         if response['status'] == 'ok':
             self.api_key = response['api_key']
         else:
             plugin.log(response)
             return False
     else:
         plugin.log(response)
     return self.api_key
示例#6
0
def _call(uri,
          params=None,
          data=None,
          cache_limit=False,
          timeout=None,
          method=None):
    timeout = timeout if timeout is not None else 5
    json_data = json.dumps(data) if data else None

    url = '%s%s' % (_base_url, uri)
    if params is not None:
        url += '?' + urllib.urlencode(params)

    plugin.log(url)
    if cache_limit is not False:
        result = _get_cached_result(url, cache_limit)
        if result:
            response = result
            plugin.log("Returning cached results")
            return response

    while True:
        try:
            request = urllib2.Request(url, data=json_data, headers=_headers)
            if method is not None:
                request.get_method = lambda: method.upper()
            f = urllib2.urlopen(request, timeout=timeout)
            result = f.read()
            response = result
            break
        except HTTPError as e:
            plugin.log(e, url)
            return False
        except URLError as e:
            plugin.log("%s: %s" % (e, url), LOG_LEVEL.VERBOSE)
            return False
        except socket.timeout as e:
            plugin.log("%s %s" % (e, url), LOG_LEVEL.VERBOSE)
            return False
    if cache_limit is not False:
        _cache_result(result, url, cache_limit)
    return response
示例#7
0
    def _call(self, method, data=None):

        url = self._build_url()
        request = self._build_request(method)
        if data:
            for key in data.keys():
                request[key] = data[key]
        json_data = json.dumps(request)
        headers = {'Content-Type': 'application/json'}
        try:
            request = urllib2.Request(url, data=json_data, headers=headers)
            f = urllib2.urlopen(request)
            response = f.read()
            return json.loads(response)
        except HTTPError as e:
            plugin.log("TransmogrifierAPI Error: %s" % e, LOG_LEVEL.VERBOSE)

        except URLError as e:
            plugin.log("TransmogrifierAPI Error: %s" % e, LOG_LEVEL.VERBOSE)
            self.raise_error(e, "TransmogrifierAPI Error", e)
            return False
        except socket.timeout as e:
            plugin.log("TransmogrifierAPI Error: %s" % e, LOG_LEVEL.VERBOSE)
            self.raise_error(e, "TransmogrifierAPI Error", e)
            return False
示例#8
0
 def get_cached_file(self, title, season=None, episode=None, year=None):
     if season is not None:
         hash = self.get_hash('tvshow', title, season, episode)
         response = self._call('get_path', {"hash": hash})
         plugin.log(response)
         if 'path' in response and response['path']:
             return {
                 "url":
                 "http://%s:%s/cached/%s" % (self.host, self.port, hash),
                 "path": response['path'],
                 "size": response['size']
             }
         return False
     else:
         hash = self.get_hash('movie', title, year)
         response = self._call('get_path', {"hash": hash})
         if 'path' in response and response['path']:
             return {
                 "url":
                 "http://%s:%s/cached/%s" % (self.host, self.port, hash),
                 "path": response['path'],
                 "size": response['size']
             }
         return False
    def _handle_request_noblock(self):
        """Handle one request, without blocking.

		I assume that select.select has returned that the socket is
		readable before this function was called, so there should be
		no risk of blocking in get_request().
		"""
        try:
            request, client_address = self.get_request()
        except socket.error, e:
            if isinstance(e.args, tuple):
                print "errno is %d" % e[0]
                if e[0] == errno.EPIPE:
                    log("Detected remote disconnect")
                else:
                    log("Socket error: %s" % e)
            else:
                log("Socket error: %s" % e)
 def http_response(self, request, response):
     plugin.log('Stopping Redirect')
     return response
def solve(url, cookie_file, user_agent, wait=True):
    headers = {'User-Agent': user_agent, 'Referer': url}
    cj = cookielib.LWPCookieJar(cookie_file)
    if cj is not None:
        try:
            cj.load(ignore_discard=True)
        except:
            pass
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        urllib2.install_opener(opener)

    request = urllib2.Request(url)
    for key in headers:
        request.add_header(key, headers[key])
    try:
        response = urllib2.urlopen(request)
        html = response.read()
    except urllib2.HTTPError as e:
        html = e.read()

    solver_pattern = 'var (?:s,t,o,p,b,r,e,a,k,i,n,g|t,r,a),f,\s*([^=]+)={"([^"]+)":([^}]+)};.+challenge-form\'\);.*?\n.*?;(.*?);a\.value'
    vc_pattern = 'input type="hidden" name="jschl_vc" value="([^"]+)'
    pass_pattern = 'input type="hidden" name="pass" value="([^"]+)'
    init_match = re.search(solver_pattern, html, re.DOTALL)
    vc_match = re.search(vc_pattern, html)
    pass_match = re.search(pass_pattern, html)

    if not init_match or not vc_match or not pass_match:
        plugin.log(
            "Couldn't find attribute: init: |%s| vc: |%s| pass: |%s| No cloudflare check?"
            % (init_match, vc_match, pass_match))
        return False

    init_dict, init_var, init_equation, equations = init_match.groups()
    vc = vc_match.group(1)
    password = pass_match.group(1)

    # log_utils.log("VC is: %s" % (vc), xbmc.LOGDEBUG)
    varname = (init_dict, init_var)
    result = int(solve_equation(init_equation.rstrip()))
    #plugin.log('Initial value: |%s| Result: |%s|' % (init_equation, result))

    for equation in equations.split(';'):
        equation = equation.rstrip()
        if equation[:len('.'.join(varname))] != '.'.join(varname):
            plugin.log('Equation does not start with varname |%s|' %
                       (equation))
        else:
            equation = equation[len('.'.join(varname)):]

        expression = equation[2:]
        operator = equation[0]
        if operator not in ['+', '-', '*', '/']:
            #plugin.log('Unknown operator: |%s|' % (equation))
            continue

        result = int(
            str(eval(str(result) + operator +
                     str(solve_equation(expression)))))
        #plugin.log('intermediate: %s = %s' % (equation, result))

    scheme = urlparse.urlparse(url).scheme
    domain = urlparse.urlparse(url).hostname
    result += len(domain)
    #plugin.log('Final Result: |%s|' % (result))

    if wait:
        plugin.log('Sleeping for 5 Seconds')
        plugin.sleep(5000)

    url = '%s://%s/cdn-cgi/l/chk_jschl?jschl_vc=%s&jschl_answer=%s&pass=%s' % (
        scheme, domain, vc, result, password)
    #plugin.log('url: %s' % (url))
    request = urllib2.Request(url)
    for key in headers:
        request.add_header(key, headers[key])
    try:
        opener = urllib2.build_opener(NoRedirection)
        urllib2.install_opener(opener)
        response = urllib2.urlopen(request)
        while response.getcode() in [301, 302, 303, 307]:
            if cj is not None:
                cj.extract_cookies(response, request)
            request = urllib2.Request(response.info().getheader('location'))
            for key in headers:
                request.add_header(key, headers[key])
            if cj is not None:
                cj.add_cookie_header(request)

            response = urllib2.urlopen(request)
        final = response.read()
    except urllib2.HTTPError as e:
        plugin.log('CloudFlare Error: %s on url: %s' % (e.code, url))
        return False

    if cj is not None:
        cj.save()
        #plugin.log('CF Save Cookies')

    return final, cj
	def connection_dropped(self, error, environ=None):
		self.kodi_disconnect = True
		plugin.log("Kodi disconnected")
from os import curdir, sep
from urlparse import urlparse
from BaseHTTPServer import BaseHTTPRequestHandler
from dudehere.routines import *
from dudehere.routines import plugin
from dudehere.routines.dispatcher import FunctionDispatcher
from dudehere.routines.scrapers import ScraperPool
from dudehere.routines import fanart
from dudehere.routines.trakt import DB as TraktDB
from dudehere.routines.trakt import TraktAPI
fanart.DB=TraktDB
fanart.trakt = TraktAPI()

HOST_ADDRESS = socket.gethostname()
LOG_FILE = vfs.join(DATA_PATH, 'access.log')
plugin.log("Setting DHCR API Access log to: %s" % LOG_FILE)

from httplib2 import Response
class RequestHandler(BaseHTTPRequestHandler):
	kodi_disconnect = False
	log_file = vfs.open(LOG_FILE, 'w')
	
	def process_cgi(self):
		parts = urlparse(self.path)
		path = parts.path
		query = parts.query
		data = cgi.parse_qs(query, keep_blank_values=True)
		arguments = path.split('/')
		return arguments, data, path

	def finish(self,*args,**kw):
	def log(self, message):
		plugin.log(message)
示例#15
0
    def onAction(self, action):
        action = action.getId()
        if action in [
                WINDOW_ACTIONS.ACTION_PREVIOUS_MENU,
                WINDOW_ACTIONS.ACTION_NAV_BACK
        ]:
            self._close()

        try:
            if action == WINDOW_ACTIONS.ACTION_MOVE_LEFT:
                controlID = self.getFocus().getId()
                index = self.getControl(CONTROLS.LISTS).getSelectedPosition()
                if index == 0: return
                to = index - 1
                liz = self.getControl(CONTROLS.LISTS).getListItem(index)
                plugin.log("move_up")
                items = []
                for i in xrange(self.getControl(CONTROLS.LISTS).size()):
                    service = self.getControl(
                        CONTROLS.LISTS).getListItem(i).getLabel()
                    items.append(service)
                items.insert(to, items.pop(index))
                self.order = items
                state_file = vfs.join(DATA_PATH, 'scrapers.cache')
                plugin.save_data(state_file, items)
                Scraper = ScraperPool(load='all')
                for scraper in items:
                    weight = 1 + items.index(scraper)
                    host = Scraper.get_scraper_by_name(scraper).name
                    Scraper.change_host_weight(host, weight)

                self.onInit()
                self.getControl(CONTROLS.LISTS).selectItem(to)

            elif action == WINDOW_ACTIONS.ACTION_MOVE_RIGHT:
                controlID = self.getFocus().getId()
                index = self.getControl(CONTROLS.LISTS).getSelectedPosition()
                if index == self.getControl(CONTROLS.LISTS).size() - 1: return
                liz = self.getControl(CONTROLS.LISTS).getListItem(index)
                to = index + 1
                plugin.log("move_down")
                items = []
                for i in xrange(self.getControl(CONTROLS.LISTS).size()):
                    service = self.getControl(
                        CONTROLS.LISTS).getListItem(i).getLabel()
                    items.append(service)
                items.insert(to, items.pop(index))
                self.order = items
                state_file = vfs.join(DATA_PATH, 'scrapers.cache')
                plugin.save_data(state_file, items)
                Scraper = ScraperPool(load='all')
                for scraper in items:
                    weight = 1 + items.index(scraper)
                    host = Scraper.get_scraper_by_name(scraper).name
                    Scraper.change_host_weight(host, weight)

                self.onInit()
                self.getControl(CONTROLS.LISTS).selectItem(to)

        except:
            pass
            return target

        return decorator

    def __coerce(self, v):
        test = v.lower()
        if test == 'none': return None
        if test == 'false': return False
        if test == "true": return True
        return v

    def error(self):
        pass

    def run(self, mode='default'):
        if mode is None or mode == '' or mode is False:
            mode = 'default'
        if mode in self.__functions:
            args = self.__args[mode]
            kwargs = self.__kwargs[mode]
            try:
                self.__functions[mode](*args, **kwargs)
            except Exception, e:
                log("Dispatcher Error in mode %s:  %s" % (mode, e))
                self.error()
        else:
            log("Illegal mode: %s" % mode)
            self.error()


dispatcher = FunctionDispatcher()