Example #1
0
    def _unshorten_adfocus(self, uri):
        orig_uri = uri
        try:

            r = requests.get(uri, headers=HTTP_HEADER, timeout=self._timeout)
            html = r.text

            adlink = re.findall("click_url =.*;", html)

            if len(adlink) > 0:
                uri = re.sub('^click_url = "|"\;$', '', adlink[0])
                if re.search(r'http(s|)\://adfoc\.us/serve/skip/\?id\=', uri):

                    http_header = copy.copy(HTTP_HEADER)
                    http_header["Host"] = "adfoc.us"
                    http_header["Referer"] = orig_uri

                    r = requests.get(uri,
                                     headers=http_header,
                                     timeout=self._timeout)

                    uri = r.url
                return uri, r.status_code
            else:
                return uri, 'No click_url variable found'
        except Exception as e:
            return uri, str(e)
Example #2
0
def ginico(url):
    import resources.lib.requests as requests

    if 'xxx&User' in url:
        x = url.partition('xxx&User')
        url = x[0] + 'xxx'
    x = url.partition('---')
    url = x[0]
    id = x[2].replace('xxx','')

    r = requests.get("http://giniko.com/watch.php?id=" + id)
    if r.text.find('m3u8?'):
        s = r.text.partition('m3u8?')
        s = s[2].partition('"')
        if len(s[0]) > 120 and len(s[0]) < 134:
            s = url + '?' + s[0]
            return s
    r = requests.get("http://giniko.com/watch.php?id=37")
    if r.text.find('m3u8?'):
        s = r.text.partition('m3u8?')
        s = s[2].partition('"')
        if len(s[0]) > 120 and len(s[0]) < 134:
            s = url + '?' + s[0]
            return s
    r = requests.get("http://giniko.com/watch.php?id=220")
    if r.text.find('m3u8?'):
        s = r.text.partition('m3u8?')
        s = s[2].partition('"')
        if len(s[0]) > 120 and len(s[0]) < 134:
            s = url + '?' + s[0]
            return s
    else: return url
Example #3
0
def ginico(url):
    import resources.lib.requests as requests

    if 'xxx&User' in url:
        x = url.partition('xxx&User')
        url = x[0] + 'xxx'
    x = url.partition('---')
    url = x[0]
    id = x[2].replace('xxx', '')

    r = requests.get("http://giniko.com/watch.php?id=" + id)
    if r.text.find('m3u8?'):
        s = r.text.partition('m3u8?')
        s = s[2].partition('"')
        if len(s[0]) > 120 and len(s[0]) < 134:
            s = url + '?' + s[0]
            return s
    r = requests.get("http://giniko.com/watch.php?id=37")
    if r.text.find('m3u8?'):
        s = r.text.partition('m3u8?')
        s = s[2].partition('"')
        if len(s[0]) > 120 and len(s[0]) < 134:
            s = url + '?' + s[0]
            return s
    r = requests.get("http://giniko.com/watch.php?id=220")
    if r.text.find('m3u8?'):
        s = r.text.partition('m3u8?')
        s = s[2].partition('"')
        if len(s[0]) > 120 and len(s[0]) < 134:
            s = url + '?' + s[0]
            return s
    else:
        return url
Example #4
0
def l1ll11ll1_SBK_(url, l1l1lllll_SBK_=l1l111_SBK_ (u"ࠧࠨ৘"), l1l11l111_SBK_=l1l111_SBK_ (u"ࠨࠩ৙")):
    l11111ll_SBK_ = l1l111_SBK_ (u"ࠩࠪ৚")
    l1llll1l1_SBK_ = HTMLParser.HTMLParser()
    if l1l1lllll_SBK_:
        email = urllib.quote(l1llll1l1_SBK_.unescape(__ADDON__.getSetting(l1l111_SBK_ (u"ࠪࡩࡲࡧࡩ࡭ࠩ৛"))))
        password = urllib.quote(l1llll1l1_SBK_.unescape(__ADDON__.getSetting(l1l111_SBK_ (u"ࠦࡵࡧࡳࡴࡹࡲࡶࡩࠨড়"))))
        l11111ll_SBK_ = requests.get(url, params=l1l111_SBK_ (u"ࠬࡲ࡯ࡨ࡫ࡱࡁࠬঢ়")+email+l1l111_SBK_ (u"࠭ࠦࡱࡣࡶࡷࡼࡵࡲࡥ࠿ࠪ৞")+password).json()
    else:
        username = urllib.quote(l1llll1l1_SBK_.unescape(__ADDON__.getSetting(l1l111_SBK_ (u"ࠧࡶࡵࡨࡶࡳࡧ࡭ࡦࠩয়"))))
        l11111ll_SBK_ = requests.get(url, params=l1l111_SBK_ (u"ࠨࡣࡳ࡭ࡤࡱࡥࡺ࠿ࠪৠ")+__ADDON__.getSetting(l1l111_SBK_ (u"ࠩࡤࡴ࡮ࡱࡥࡺࠩৡ"))+l1l111_SBK_ (u"ࠪࠪࡺࡹࡥࡳࡰࡤࡱࡪࡃࠧৢ")+username).json()
    if l1l11l111_SBK_:
        username = urllib.quote(l1llll1l1_SBK_.unescape(__ADDON__.getSetting(l1l111_SBK_ (u"ࠫࡺࡹࡥࡳࡰࡤࡱࡪ࠭ৣ"))))
        l11111ll_SBK_ = requests.post(url, data=l1l11l111_SBK_, params=l1l111_SBK_ (u"ࠬࡧࡰࡪࡡ࡮ࡩࡾࡃࠧ৤")+__ADDON__.getSetting(l1l111_SBK_ (u"࠭ࡡࡱ࡫࡮ࡩࡾ࠭৥"))+l1l111_SBK_ (u"ࠧࠧࡷࡶࡩࡷࡴࡡ࡮ࡧࡀࠫ০")+username).json()
    return l11111ll_SBK_
Example #5
0
def __getTrakt(url, post=None, noget=None):
    try:
        url = urlparse.urljoin(BASE_URL, url)
        post = json.dumps(post, ensure_ascii=False) if post else None
        headers = {'Content-Type': 'application/json',
                    'trakt-api-key': V2_API_KEY,
                    'trakt-api-version': '2',
                    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0',
                    'Accept-Language': 'en-US'}

        if getTraktCredentialsInfo():
            headers.update({'Authorization': 'Bearer %s' % xbmcaddon.Addon().getSetting('trakt.token')})
        askd = requests.post(url, data=post, headers=headers) if post or noget else requests.get(url, data=post, headers=headers)

        resp_code = askd.status_code
        resp_header = json.dumps(dict(askd.headers))
        result = askd.content if post and not noget else askd.json()

        if resp_code in ['500', '502', '503', '504', '520', '521', '522', '524']:
            xbmc.log("### [%s]: Temporary Trakt Error: %s" % ('Trakt',resp_code,), level=xbmc.LOGNOTICE )
            return
        elif resp_code in ['404']:
            xbmc.log("### [%s]: Object Not Found : %s" % ('Trakt',resp_code,), level=xbmc.LOGNOTICE )
            return
        elif resp_code in ['429']:
            xbmc.log("### [%s]: Trakt Rate Limit Reached: %s" % ('Trakt',resp_code,), level=xbmc.LOGNOTICE )
            return

        if resp_code not in ['401', '405']:
            return result, resp_header

        oauth = urlparse.urljoin(BASE_URL, '/oauth/token')
        opost = {'client_id': V2_API_KEY, 'client_secret': CLIENT_SECRET, 'redirect_uri': REDIRECT_URI, 'grant_type': 'refresh_token', 'refresh_token': xbmcaddon.Addon().getSetting('trakt.refresh')}
        opost = urllib.urencode(byteify(json.dumps(opost)))
        result = requests.post(oauth, data=opost, headers=headers)
        result = result.content

        token, refresh = result['access_token'], result['refresh_token']

        xbmcaddon.Addon().setSetting(id='trakt.token', value=token)
        xbmcaddon.Addon().setSetting(id='trakt.refresh', value=refresh)

        headers['Authorization'] = 'Bearer %s' % token

        result = requests.get(url, data=post, headers=headers)
        return result.content, dict(result.headers)
    except BaseException as e:
        xbmc.log("### [%s]: MRSP getTrakt Unknown Trakt Error: %s" % ('Trakt',e,), level=xbmc.LOGNOTICE )
        pass
Example #6
0
    def _unshorten_adfly(self, uri):

        try:
            r = requests.get(uri, headers=HTTP_HEADER, timeout=self._timeout)
            html = r.text
            ysmm = re.findall(r"var ysmm =.*\;?", html)

            if len(ysmm) > 0:
                ysmm = re.sub(r'var ysmm \= \'|\'\;', '', ysmm[0])

                left = ''
                right = ''

                for c in [ysmm[i:i + 2] for i in range(0, len(ysmm), 2)]:
                    left += c[0]
                    right = c[1] + right

                decoded_uri = b64decode(left.encode() +
                                        right.encode())[2:].decode()

                if re.search(r'go\.php\?u\=', decoded_uri):
                    decoded_uri = b64decode(re.sub(r'(.*?)u=', '',
                                                   decoded_uri)).decode()

                return decoded_uri, r.status_code
            else:
                return uri, 'No ysmm variable found'

        except Exception as e:
            return uri, str(e)
Example #7
0
def l1l111111_SBK_(url,path):
    l1l11111l_SBK_ = requests.get(url.encode(l1l111_SBK_ (u"࠭ࡵࡵࡨ࠰࠼ࠬਖ"))).content
    if l1l11111l_SBK_:
        with open(path, l1l111_SBK_ (u"ࠧࡸࠩਗ")) as fh:
            fh.write(l1l11111l_SBK_)
            fh.close()
    return url
Example #8
0
def iptvxtra_play():
    idx = mode.replace("?playkurd=", "").replace("###", "|").replace(
        "#x#", "?").replace("#h#", "http://").split('***')
    xbmc.executebuiltin('XBMC.Notification(' + idx[1] + ' , KARWANTV ,5000,' +
                        idx[2] + ')')

    if idx[0] <> '':
        xxx = idx[0].decode(md5)
        ref = xxx.replace('live/', '').replace('php', 'html')
        r = requests.get(xxx, headers={"Referer": ref})
        r = r.text.strip().replace('\n', ' ')
        xxx = find_between(r, 'file:', ',')
        idx[0] = xxx.replace(' ',
                             '').replace("'", "").replace('"', '').replace(
                                 '}', '').replace('manifest.f4m',
                                                  'playlist.m3u8').strip()
        iudy = '73776655726C3D687474703A2F2F702E6A777063646E2E636F6D2F362F31312F6A77706C617965722E666C6173682E737766207061676555726C3D687474703A2F2F6B617277616E2E7476206C6976653D31'
        if 'rtmp://' in idx[0]: idx[0] = idx[0] + ' ' + iudy.decode(md5)

    xbmcPlayer = xbmc.Player()
    listitem = xbmcgui.ListItem(idx[1],
                                iconImage=idx[2],
                                thumbnailImage=idx[2])
    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    playlist.clear()
    playlist.add(idx[0], listitem)
    xbmcPlayer.play(playlist, None, False)
    sys.exit(0)
Example #9
0
def get_status(stat):
    try:
        wert = hashlib.md5('#user='******'pass='******'loc': wert,'la':'AR','stat':str(stat)}
        r = requests.get("http://www.iptvxtra.net/xbmc/_form/rsx.php", params=payload)
        urln = r.text.strip() 
        if 'not allowed' in urln:
            xbmc.executebuiltin('XBMC.Notification(Login Fehler , der Zugang über einen Proxy oder Tor-IPs ist nicht erlaubt ,25000,'+net+')')
            sys.exit(0)
        if 'none.xml' in urln:
            xbmc.executebuiltin('XBMC.Notification(Login Fehler , du bist noch nicht registriert ,25000,'+net+')')
            sys.exit(0)
        if 'nonex.xml' in urln:
            xbmc.executebuiltin('XBMC.Notification(Netzwerkfehler HTTP-401 , Passwort oder User ist sehr wahrscheinlich verkehrt ,25000,'+net+')')
            sys.exit(0)
        if 'lockland.xml' in urln:
            xbmc.executebuiltin('XBMC.Notification(Login Fehler , dieses Addon ist in deinem Land nicht verfügbar ,25000,'+net+')')
            sys.exit(0)
        if 'proxy.xml' in urln:
            xbmc.executebuiltin('XBMC.Notification(Login Fehler , der Zugang über einen Proxy oder Tor-IPs ist nicht erlaubt ,25000,'+net+')')
            sys.exit(0)
        url = urln.split('###')
        return url[1]

    except:
        xbmc.executebuiltin('XBMC.Notification(Netzwerkfehler , fehlerhafter Zugang zum Login-Server,25000,'+net+')')
        sys.exit(0)
Example #10
0
def auth():
    try:
        lox = hashlib.md5('#user='******'pass='******'loc': lox, 'h': '0', 'sh': 'servhost', 'la': 'Q'}
        r = requests.get("http://www.iptvxtra.net/xbmc/_form/rsx.php",
                         params=payload)
        if '6B.5.26469.3.4616E5F.3' == r.text.strip():
            xbmc.executebuiltin(
                'XBMC.Notification(Login Fehler , KARWAN TV ,20000,' + iconx +
                ')')
            xbmcaddon.Addon("plugin.video.iptvxtra-kurdtv").openSettings()
            sys.exit(0)
        if '6B.5.26469.3.469995F.3' == r.text.strip():
            xbmc.executebuiltin(
                'XBMC.Notification(Login Fehler , KARWAN TV ,30000,' + iconx +
                ')')
            sys.exit(0)
        linx = r.text.replace('.', '7').replace(
            '/', 'A').strip().decode(md5).split('***')
        req = urllib2.Request(linx[0])
        req.add_header('Referer', linx[1])
        response = urllib2.urlopen(req)
        frame = response.read()
    except:
        frame = ''
    return frame
Example #11
0
def get_url():

    basicurl = 'http://tvpstream.tvp.pl/'
    plurl = requests.get(basicurl)
    pattern = '<div class="button.*?data-video_id="([^"]+)" title="([^"]+)">.*?<img src="([^"]+)".*?</div>'
    rResult = parse(plurl.text, pattern)
    return rResult[1]
Example #12
0
def get_url():

    basicurl = 'http://tvpstream.tvp.pl/'
    plurl = requests.get(basicurl)
    pattern = '<div class="button.*?data-video_id="([^"]+)" title="([^"]+)">.*?<img src="([^"]+)".*?</div>'
    rResult = parse(plurl.text, pattern)
    return rResult[1]
Example #13
0
def GetData(url, params=None):
    session = TEMP_CACHE.get('cookie')
    cookies = dict(sessionid=str(session))
    proxies = None
    headers = {}
    if PROXYUSER != '' and PROXYPASS != '' and PROXYURL != '':
        headers['Proxy-Authorization'] = 'Basic %s' % base64.b64encode(
            '%s:%s' % (PROXYUSER, PROXYPASS))
        proxies = {'http': 'http://%s' % (PROXYURL)}
    elif PROXYUSER == '' and PROXYPASS == '' and PROXYURL != '':
        proxies = {'http': 'http://%s' % (PROXYURL)}
    response = requests.get(url,
                            params=params,
                            cookies=cookies,
                            proxies=proxies,
                            headers=headers)
    cookies = requests.utils.dict_from_cookiejar(response.cookies)
    if 'sessionid' in cookies:
        TEMP_CACHE.set('cookie', cookies['sessionid'])
    if response.text == 'rate limit exceeded':
        warning = 'You can\'t skip songs that quickly.'
        display_time = 2000  # in milliseconds
        xbmc.executebuiltin('Notification(%s, %s, %d, %s)' %
                            (ADDONNAME, warning, display_time, ICON))
        return None
    data = response.json()
    return data
Example #14
0
def l1l111111_SBK_(url, path):
    l1l11111l_SBK_ = requests.get(url.encode(l1l111_SBK_(u"࠭ࡵࡵࡨ࠰࠼ࠬਖ"))).content
    if l1l11111l_SBK_:
        with open(path, l1l111_SBK_(u"ࠧࡸࠩਗ")) as fh:
            fh.write(l1l11111l_SBK_)
            fh.close()
    return url
Example #15
0
def iptvxtra_play():
    idx = mode.replace("?playkurd=", "").replace("###", "|").replace("#x#", "?").replace("#h#", "http://").split("***")
    xbmc.executebuiltin("XBMC.Notification(" + idx[1] + " , KARWAN:TV ,5000," + idx[2] + ")")

    if idx[0] <> "":
        import resources.lib.requests as requests

        xxx = idx[0]
        ref = xxx.replace("live/", "").replace("php", "html")
        r = requests.get(xxx, headers={"Referer": ref})
        r = r.text.strip().replace("\n", " ")
        # print r.encode('utf-8')
        xxx = find_between(r, "file:", ",")
        idx[0] = xxx.replace(" ", "").replace("'", "").replace('"', "").replace("}", "").strip()
        # print idx[0]
        if "rtmp://" in idx[0]:
            idx[0] = idx[0] + " swfUrl=http://p.jwpcdn.com/6/11/jwplayer.flash.swf pageUrl=http://karwan.tv live=1"

    xbmcPlayer = xbmc.Player()
    listitem = xbmcgui.ListItem(idx[1], iconImage=idx[2], thumbnailImage=idx[2])
    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    playlist.clear()
    playlist.add(idx[0], listitem)
    xbmcPlayer.play(playlist, None, False)
    sys.exit(0)
Example #16
0
def canlitvlive(url):
    import resources.lib.requests as requests
    r = requests.get(url)
    r = r.text.replace(' ', '').strip()
    r = find_between(r, 'file:"http', '"')
    #r = 'http'+r+'|referer=http://www.canlitvlive.com/tvplayer.swf'
    r = 'http' + r + '|referer=http://www.canlitvlive.com/jwplayer.flash.swf'
    return r
Example #17
0
def canlitvlive(url):
    import resources.lib.requests as requests
    r = requests.get(url)
    r = r.text.replace(' ','').strip()
    r = find_between(r,'file:"http','"')
    #r = 'http'+r+'|referer=http://www.canlitvlive.com/tvplayer.swf'
    r = 'http'+r+'|referer=http://www.canlitvlive.com/jwplayer.flash.swf'
    return r
Example #18
0
    def unwrap_30x(self, uri, timeout=10):

        domain = urlsplit(uri).netloc
        self._timeout = timeout

        loop_counter = 0
        try:

            if loop_counter > 5:
                raise ValueError("Infinitely looping redirect from URL: '%s'" %
                                 (uri, ))

            # headers stop t.co from working so omit headers if this is a t.co link
            if domain == 't.co':
                r = requests.get(uri, timeout=self._timeout)
                return r.url, r.status_code
            # p.ost.im uses meta http refresh to redirect.
            if domain == 'p.ost.im':
                r = requests.get(uri,
                                 headers=HTTP_HEADER,
                                 timeout=self._timeout)
                uri = re.findall(r'.*url\=(.*?)\"\.*', r.text)[0]
                return uri, r.status_code
            else:

                while True:
                    try:
                        r = requests.head(uri,
                                          headers=HTTP_HEADER,
                                          timeout=self._timeout)
                    except (requests.exceptions.InvalidSchema,
                            requests.exceptions.InvalidURL):
                        return uri, -1

                    retries = 0
                    if 'location' in r.headers and retries < self._maxretries:
                        r = requests.head(r.headers['location'])
                        uri = r.url
                        loop_counter += 1
                        retries = retries + 1
                    else:
                        return r.url, r.status_code

        except Exception as e:
            return uri, str(e)
Example #19
0
def canlitvlive(url):
    import resources.lib.requests as requests
    r = requests.get(url)
    r = r.text.replace(' ','').strip()
    # print r
    r = find_between(r,'file:"http','"')
    #r = 'http'+r+'|referer=http://www.canlitvlive.com/tvplayer.swf'
    r = 'http'+r+'|User-Agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:18.0) Gecko/20100101 Firefox/18.0&referer=http://www.canlitvlive.org/jwplayer.flash.swf'
    return r
Example #20
0
def canlitvlive(url):
    import resources.lib.requests as requests
    r = requests.get(url)
    r = r.text.replace(' ', '').strip()
    # print r
    r = find_between(r, 'file:"http', '"')
    #r = 'http'+r+'|referer=http://www.canlitvlive.com/tvplayer.swf'
    r = 'http' + r + '|User-Agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:18.0) Gecko/20100101 Firefox/18.0&referer=http://www.canlitvlive.org/jwplayer.flash.swf'
    return r
Example #21
0
    def _unshorten_lnxlu(self, uri):
        try:
            r = requests.get(uri, headers=HTTP_HEADER, timeout=self._timeout)
            html = r.text

            code = re.findall('/\?click\=(.*)\."', html)

            if len(code) > 0:
                payload = {'click': code[0]}
                r = requests.get('http://lnx.lu/',
                                 params=payload,
                                 headers=HTTP_HEADER,
                                 timeout=self._timeout)
                return r.url, r.status_code
            else:
                return uri, 'No click variable found'
        except Exception as e:
            return uri, str(e)
Example #22
0
def get_status():
    try:
        r = requests.get("http://api.iptvxtra.net/tophits.php", params = {'loc': mdx ,'la':'DE','app':'tophits1'} )
        url = r.text.strip().decode("hex") 
    except:
        xbmc.executebuiltin('XBMC.Notification(Netzwerkfehler , fehlerhafter Zugang zum Login-Server,25000,'+net+')')
        sys.exit(0)
    if url == '':
        xbmc.executebuiltin('XBMC.Notification(Netzwerkfehler , fehlerhafter Zugang zum Login-Server,25000,'+net+')')
        sys.exit(0)
    return url
Example #23
0
def auth():
    try:
        payload = {'loc': '6B757264697374616E','h':'0','sh':'servhost','la':'Q'}
        r = requests.get("http://www.iptvxtra.net/xbmc/_form/rsx.php", params=payload)
        linx = r.text.replace('.','7').replace('/','A').decode(md5).split('***')
        req = urllib2.Request(linx[0])
        req.add_header('Referer', linx[1])
        response = urllib2.urlopen(req)
        frame = response.read()
    except: frame = ''
    return frame
def search_for(search_criteria):
    search_safe = urllib.quote_plus(search_criteria)
    search_url = "http://www.pluralsight.com/metadata/live/search?query=" + search_safe
    search_headers = {
        "Accept-Language": "en-us",
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Accept-Encoding": "gzip"
    }
    debug_log_duration("Hitting: " + search_url)
    response = requests.get(search_url, headers=search_headers)
    return response.json()
def search_for(search_criteria):
    search_safe = urllib.quote_plus(search_criteria)
    search_url = "https://www.pluralsight.com/metadata/live/search?query=" + search_safe
    search_headers = {
        "Accept-Language": "en-us",
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Accept-Encoding": "gzip"
    }
    debug_log_duration("Hitting: " + search_url)
    response = requests.get(search_url, headers=search_headers)
    return response.json()
Example #26
0
    def _unshorten_shst(self, uri):
        try:
            r = requests.get(uri, headers=HTTP_HEADER, timeout=self._timeout)
            html = r.text

            session_id = re.findall(r'sessionId\:(.*?)\"\,', html)
            if len(session_id) > 0:
                session_id = re.sub(r'\s\"', '', session_id[0])

                http_header = copy.copy(HTTP_HEADER)
                http_header[
                    "Content-Type"] = "application/x-www-form-urlencoded"
                http_header["Host"] = "sh.st"
                http_header["Referer"] = uri
                http_header["Origin"] = "http://sh.st"
                http_header["X-Requested-With"] = "XMLHttpRequest"

                time.sleep(5)

                payload = {'adSessionId': session_id, 'callback': 'c'}
                r = requests.get('http://sh.st/shortest-url/end-adsession',
                                 params=payload,
                                 headers=http_header,
                                 timeout=self._timeout)
                response = r.content[6:-2].decode('utf-8')

                if r.status_code == 200:
                    resp_uri = json.loads(response)['destinationUrl']
                    if resp_uri is not None:
                        uri = resp_uri
                    else:
                        return uri, 'Error extracting url'
                else:
                    return uri, 'Error extracting url'

            return uri, r.status_code

        except Exception as e:
            return uri, str(e)
Example #27
0
def get_status():
    load = {'name': user,'passwd': pwd}
    try:
        r = requests.get("http://xbmc.streamnetwork.tv/api.php", params=load)
    except:
        xbmc.executebuiltin('XBMC.Notification(Netzwerk Fehler , der Login Server ist nicht erreichbar ,7000,'+icon+')')
        sys.exit(0)
    lista = r.text
    lista = lista.strip()
    if 'freeuser' in lista: free = 0
    elif 'reguser' in lista: free = 1
    elif 'Premium' in lista: free = 2
    else: free = 0
    return free
Example #28
0
def GetData(url, params=None):
    session = TEMP_CACHE.get('cookie')
    cookies = dict(sessionid=str(session))
    response = requests.get(url, params=params, cookies=cookies)
    cookies = requests.utils.dict_from_cookiejar(response.cookies)
    if 'sessionid' in cookies:
        TEMP_CACHE.set('cookie', cookies['sessionid'])
    if response.text == 'rate limit exceeded':
        warning = 'You can\'t skip songs that quickly.'
        display_time = 2000  # in milliseconds
        xbmc.executebuiltin('Notification(%s, %s, %d, %s)' % (ADDONNAME, warning, display_time, ICON))
        return None
    data = response.json()
    return data
def bookmarks_view(catalogue):
    bookmark_url = "https://app.pluralsight.com/data/bookmarks"
    headers = {
        "Accept-Language": "en-us",
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Accept-Encoding": "gzip"
    }
    debug_log_duration("Getting bookmarked courses: " + bookmark_url)
    token = login(catalogue)
    response = requests.get(bookmark_url, headers=headers, cookies=catalogue.cookies)
    results = response.json()
    debug_log_duration("Response: " + str(results))
    courses = [catalogue.get_course_by_name(x['courseName']) for x in results]
    courses_view(courses)
Example #30
0
def l1ll11ll1_SBK_(url,
                   l1l1lllll_SBK_=l1l111_SBK_(u"ࠧࠨ৘"),
                   l1l11l111_SBK_=l1l111_SBK_(u"ࠨࠩ৙")):
    l11111ll_SBK_ = l1l111_SBK_(u"ࠩࠪ৚")
    l1llll1l1_SBK_ = HTMLParser.HTMLParser()
    if l1l1lllll_SBK_:
        email = urllib.quote(
            l1llll1l1_SBK_.unescape(
                __ADDON__.getSetting(l1l111_SBK_(u"ࠪࡩࡲࡧࡩ࡭ࠩ৛"))))
        password = urllib.quote(
            l1llll1l1_SBK_.unescape(
                __ADDON__.getSetting(l1l111_SBK_(u"ࠦࡵࡧࡳࡴࡹࡲࡶࡩࠨড়"))))
        l11111ll_SBK_ = requests.get(url,
                                     params=l1l111_SBK_(u"ࠬࡲ࡯ࡨ࡫ࡱࡁࠬঢ়") + email +
                                     l1l111_SBK_(u"࠭ࠦࡱࡣࡶࡷࡼࡵࡲࡥ࠿ࠪ৞") +
                                     password).json()
    else:
        username = urllib.quote(
            l1llll1l1_SBK_.unescape(
                __ADDON__.getSetting(l1l111_SBK_(u"ࠧࡶࡵࡨࡶࡳࡧ࡭ࡦࠩয়"))))
        l11111ll_SBK_ = requests.get(
            url,
            params=l1l111_SBK_(u"ࠨࡣࡳ࡭ࡤࡱࡥࡺ࠿ࠪৠ") +
            __ADDON__.getSetting(l1l111_SBK_(u"ࠩࡤࡴ࡮ࡱࡥࡺࠩৡ")) +
            l1l111_SBK_(u"ࠪࠪࡺࡹࡥࡳࡰࡤࡱࡪࡃࠧৢ") + username).json()
    if l1l11l111_SBK_:
        username = urllib.quote(
            l1llll1l1_SBK_.unescape(
                __ADDON__.getSetting(l1l111_SBK_(u"ࠫࡺࡹࡥࡳࡰࡤࡱࡪ࠭ৣ"))))
        l11111ll_SBK_ = requests.post(
            url,
            data=l1l11l111_SBK_,
            params=l1l111_SBK_(u"ࠬࡧࡰࡪࡡ࡮ࡩࡾࡃࠧ৤") +
            __ADDON__.getSetting(l1l111_SBK_(u"࠭ࡡࡱ࡫࡮ࡩࡾ࠭৥")) +
            l1l111_SBK_(u"ࠧࠧࡷࡶࡩࡷࡴࡡ࡮ࡧࡀࠫ০") + username).json()
    return l11111ll_SBK_
def recent_view(catalogue):
    recent_url = "https://app.pluralsight.com/data/user/history"
    headers = {
        "Accept-Language": "en-us",
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Accept-Encoding": "gzip"
    }
    debug_log_duration("Getting recently watched courses: " + recent_url)
    token = login(catalogue)
    response = requests.get(recent_url, headers=headers, cookies=catalogue.cookies)
    results = response.json()
    debug_log_duration("Response: " + str(results))
    courses = [catalogue.get_course_by_name(x['course']['name']) for x in results][:10]
    courses_view(courses)
Example #32
0
def StoreIcon(icon_id):
    thumbnail_sizes = {
        '1': 50,
        '2': 100,
        '3': 200,
        '4': 500,
        '5': 1000
    }

    day_in_seconds = 24 * 60 * 60
    thumb_ages = {
        '1': day_in_seconds,
        '2': 2 * day_in_seconds,
        '3': 5 * day_in_seconds,
        '4': 15 * day_in_seconds,
        '5': 30 * day_in_seconds
    }

    if not xbmcvfs.exists(CACHE_DIR):
        xbmcvfs.mkdir(CACHE_DIR)

    filePath = CACHED_ICON_FILE % icon_id
    if xbmcvfs.exists(filePath):
        if THUMB_AGE == '0':
            return filePath

        info = os.stat(xbmc.translatePath(filePath))
        filetime = info.st_mtime
        now = time.time()
        diff = now - filetime
        limit = thumb_ages[THUMB_AGE] if THUMB_AGE else thumb_ages['5']

        if diff < limit:
            return filePath
        else:
            xbmcvfs.delete(filePath)

    size = thumbnail_sizes[THUMB_SIZE] if THUMB_SIZE else thumbnail_sizes['3']
    url = 'http://songza.com/api/1/station/%s/image?size=%s' % (icon_id, size)
    response = requests.get(url)
    if response.status_code == 200:
        dataFile = open(xbmc.translatePath(filePath), 'wb')
        for chunk in response.iter_content():
            dataFile.write(chunk)
        dataFile.close()
        response.close()

    return filePath
Example #33
0
def get_status():
    load = {'name': user, 'passwd': pwd}
    try:
        r = requests.get("http://xbmc.streamnetwork.tv/api.php", params=load)
    except:
        xbmc.executebuiltin(
            'XBMC.Notification(Netzwerk Fehler , der Login Server ist nicht erreichbar ,7000,'
            + icon + ')')
        sys.exit(0)
    lista = r.text
    lista = lista.strip()
    if 'freeuser' in lista: free = 0
    elif 'reguser' in lista: free = 1
    elif 'Premium' in lista: free = 2
    else: free = 0
    return free
def recent_view(catalogue):
    try:
        recent_url = "https://app.pluralsight.com/data/user/history"
        headers = {
            "Accept-Language": "en-us",
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Accept-Encoding": "gzip"
        }
        debug_log_duration("Getting recently watched courses: " + recent_url)
        login(catalogue)
        response = requests.get(recent_url, headers=headers, cookies=catalogue.cookies)
        results = response.json()
        debug_log_duration("Response: " + str(results))
        courses = [catalogue.get_course_by_name(x['course']['name']) for x in results][:10]
        courses_view(courses)
    except AuthorisationError:
        display_auth_error()
Example #35
0
def auth():
    try:
        lox = hashlib.md5('#user='******'pass='******'loc': lox,'h':'0','sh':'servhost','la':'Q'}
        r = requests.get("http://www.iptvxtra.net/xbmc/_form/rsx.php", params=payload)
        if '6B.5.26469.3.4616E5F.3' == r.text.strip():
            xbmc.executebuiltin('XBMC.Notification(Login Fehler , KARWAN TV ,20000,'+iconx+')')
            xbmcaddon.Addon("plugin.video.iptvxtra-kurdtv").openSettings()
            sys.exit(0)
        if '6B.5.26469.3.469995F.3' == r.text.strip():
            xbmc.executebuiltin('XBMC.Notification(Login Fehler , KARWAN TV ,30000,'+iconx+')')
            sys.exit(0)
        linx = r.text.replace('.','7').replace('/','A').strip().decode(md5).split('***')
        req = urllib2.Request(linx[0])
        req.add_header('Referer', linx[1])
        response = urllib2.urlopen(req)
        frame = response.read()
    except: frame = ''
    return frame
Example #36
0
def auth():
    try:
        payload = {
            'loc': '6B757264697374616E',
            'h': '0',
            'sh': 'servhost',
            'la': 'Q'
        }
        r = requests.get("http://www.iptvxtra.net/xbmc/_form/rsx.php",
                         params=payload)
        linx = r.text.replace('.', '7').replace('/',
                                                'A').decode(md5).split('***')
        req = urllib2.Request(linx[0])
        req.add_header('Referer', linx[1])
        response = urllib2.urlopen(req)
        frame = response.read()
    except:
        frame = ''
    return frame
Example #37
0
def StoreIcon(icon_id):
    thumbnail_sizes = {'1': 50, '2': 100, '3': 200, '4': 500, '5': 1000}

    day_in_seconds = 24 * 60 * 60
    thumb_ages = {
        '1': day_in_seconds,
        '2': 2 * day_in_seconds,
        '3': 5 * day_in_seconds,
        '4': 15 * day_in_seconds,
        '5': 30 * day_in_seconds
    }

    if not xbmcvfs.exists(CACHE_DIR):
        xbmcvfs.mkdir(CACHE_DIR)

    filePath = CACHED_ICON_FILE % icon_id
    if xbmcvfs.exists(filePath):
        if THUMB_AGE == '0':
            return filePath

        info = os.stat(xbmc.translatePath(filePath))
        filetime = info.st_mtime
        now = time.time()
        diff = now - filetime
        limit = thumb_ages[THUMB_AGE] if THUMB_AGE else thumb_ages['5']

        if diff < limit:
            return filePath
        else:
            xbmcvfs.delete(filePath)

    size = thumbnail_sizes[THUMB_SIZE] if THUMB_SIZE else thumbnail_sizes['3']
    url = 'http://songza.com/api/1/station/%s/image?size=%s' % (icon_id, size)
    response = requests.get(url)
    if response.status_code == 200:
        dataFile = open(xbmc.translatePath(filePath), 'wb')
        for chunk in response.iter_content():
            dataFile.write(chunk)
        dataFile.close()
        response.close()

    return filePath
Example #38
0
def get_status():
    try:
        r = requests.get("http://api.iptvxtra.net/tophits.php",
                         params={
                             'loc': mdx,
                             'la': 'DE',
                             'app': 'serien1'
                         })
        url = r.text.strip().decode("hex")
    except:
        xbmc.executebuiltin(
            'XBMC.Notification(Netzwerkfehler , fehlerhafter Zugang zum Login-Server,25000,'
            + net + ')')
        sys.exit(0)
    if url == '':
        xbmc.executebuiltin(
            'XBMC.Notification(Netzwerkfehler , fehlerhafter Zugang zum Login-Server,25000,'
            + net + ')')
        sys.exit(0)
    return url
def bookmarks_view(catalogue):
    try :
        bookmark_url = "https://app.pluralsight.com/data/bookmarks"
        headers = {
            "Accept-Language": "en-us",
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Accept-Encoding": "gzip"
        }
        debug_log_duration("Getting bookmarked courses: " + bookmark_url)
        login(catalogue)
        response = requests.get(bookmark_url, headers=headers, cookies=catalogue.cookies)
        if response.status_code == 403:
            raise AuthorisationError
        results = response.json()
        debug_log_duration("Response: " + str(results))
        courses = [catalogue.get_course_by_name(x['courseName']) for x in results]
        courses_view(courses)
    except AuthorisationError:
        display_auth_error()
Example #40
0
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if xbmcgui.Dialog().yesno("Trakt", "An account already exists.", "Do you want to reset?", ''):
                xbmcaddon.Addon().setSetting(id='trakt.user', value='')
                xbmcaddon.Addon().setSetting(id='trakt.token', value='')
                xbmcaddon.Addon().setSetting(id='trakt.refresh', value='')
            else: return
        result = getTraktAsJson('/oauth/device/code', {'client_id': V2_API_KEY}, '1')
        verification_url = ("1) Visit : [COLOR skyblue]%s[/COLOR]" % result['verification_url']).encode('utf-8')
        user_code = ("2) When prompted enter : [COLOR skyblue]%s[/COLOR]" % result['user_code']).encode('utf-8')
        expires_in = int(result['expires_in'])
        device_code = result['device_code']
        interval = result['interval']

        progressDialog = xbmcgui.DialogProgress()
        progressDialog.create('Trakt', verification_url, user_code)

        for i in range(0, expires_in):
            try:
                if progressDialog.iscanceled(): break
                time.sleep(1)
                if not float(i) % interval == 0: raise Exception()
                r = getTraktAsJson('/oauth/device/token', {'client_id': V2_API_KEY, 'client_secret': CLIENT_SECRET, 'code': device_code}, '1')
                if 'access_token' in r: break
            except:
                pass
        try: progressDialog.close()
        except: pass
        token, refresh = r['access_token'], r['refresh_token']
        headers = {'Content-Type': 'application/json', 'trakt-api-key': V2_API_KEY, 'trakt-api-version': '2', 'Authorization': 'Bearer %s' % token}
        result = requests.get(urlparse.urljoin(BASE_URL, '/users/me'), headers=headers)
        result = result.json()
        user = result['username']

        xbmcaddon.Addon().setSetting(id='trakt.user', value=user)
        xbmcaddon.Addon().setSetting(id='trakt.token', value=token)
        xbmcaddon.Addon().setSetting(id='trakt.refresh', value=refresh)
    except Exception as e:
        xbmc.log("### [%s]: MRSP AuthTrakt: %s" % ('Trakt',e,), level=xbmc.LOGNOTICE )
        pass
def play_view(catalogue):
    # List of qualities to cycle through until a good one is found.
    # This seem to be all the ones PluralSight supports
    # Added because some videos seemed to lack some quality options
    qualities = [
                 "1280x720mp4",
                 "1024x768mp4",
                 "848x640mp4", 
                 "640x480mp4", 
                 ]
                 
    module_name = g_args.get('module_name', None)[0]
    course_name = g_args.get('course_name', None)[0]
    clip_id = g_args.get('clip_id', None)[0]
    clip = catalogue.get_clip_by_id(clip_id, module_name, course_name)
    found = False
    
    for quality in qualities:
        url = clip.get_url(g_username, quality)
        debug_log_duration("Getting video url for: " + url)
        try:
            video_url = get_video_url(url, catalogue.token)
        except AuthorisationError:
            debug_log_duration("Session has expired, re-authorising.")
            token = login(catalogue)
            video_url = get_video_url(url, token)
        except VideoNotFoundError:
            debug_log_duration("Quality doesn't exist, moving on...")
            continue
        debug_log_duration("Got video url: " + video_url)
        # Test that the url is good, otherwise move on
        response = requests.get(video_url)
        if response.status_code in (403, 404):
            debug_log_duration("URL is bad, moving on...")
            continue
        else:
            debug_log_duration("URL is good, continuing...")
            break
                
    li = xbmcgui.ListItem(path=video_url)
    xbmcplugin.setResolvedUrl(handle=g_addon_handle, succeeded=True, listitem=li)
Example #42
0
def GetData(url, params=None):
    session = TEMP_CACHE.get('cookie')
    cookies = dict(sessionid=str(session))
    proxies = None
    headers = {}
    if PROXYUSER != '' and PROXYPASS != '' and PROXYURL != '':
        headers['Proxy-Authorization'] = 'Basic %s' % base64.b64encode('%s:%s' % (PROXYUSER, PROXYPASS))
        proxies = { 'http': 'http://%s' % (PROXYURL) }
    elif PROXYUSER == '' and PROXYPASS == '' and PROXYURL != '':
        proxies = { 'http': 'http://%s' % (PROXYURL) }
    response = requests.get(url, params=params, cookies=cookies, proxies=proxies, headers=headers)
    cookies = requests.utils.dict_from_cookiejar(response.cookies)
    if 'sessionid' in cookies:
        TEMP_CACHE.set('cookie', cookies['sessionid'])
    if response.text == 'rate limit exceeded':
        warning = 'You can\'t skip songs that quickly.'
        display_time = 2000  # in milliseconds
        xbmc.executebuiltin('Notification(%s, %s, %d, %s)' % (ADDONNAME, warning, display_time, ICON))
        return None
    data = response.json()
    return data
Example #43
0
def fetchData(url, referer=None, data={}, redirect=None, rtype=None, headers={}, cookies={}):
    from resources.lib.requests.packages.urllib3.exceptions import InsecureRequestWarning
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    timeout = int(__settings__.getSetting('timeout'))
    headers = headers
    if referer != None:
        headers['Referer'] = referer
    headers['User-Agent'] = USERAGENT
    try:
        if data: get = requests.post(url, headers=headers, data=data, verify=False, timeout=timeout)
        else: get = requests.get(url, headers=headers, verify=False, timeout=timeout, cookies=cookies)
        if redirect: result = get.url
        else: 
            if rtype: 
                if rtype == 'json': result = get.json()
                else: result = get.text
            else: result = get.content
        return (result)
    except BaseException as e:
        log(" fetchData(" + url + ") exception: " + str(e))
        return
Example #44
0
def iptvxtra_play():
    idx = mode.replace("?playkurd=", "").replace("###", "|").replace("#x#", "?").replace("#h#", "http://").split('***')
    xbmc.executebuiltin('XBMC.Notification('+idx[1]+' , KARWANTV ,5000,'+idx[2]+')')

    if idx[0] <> '':
        xxx = idx[0].decode(md5)
        ref = xxx.replace('live/','').replace('php','html')
        r = requests.get(xxx, headers={"Referer": ref})
        r = r.text.strip().replace('\n',' ')
        xxx = find_between(r,'file:',',')
        idx[0] = xxx.replace(' ','').replace("'","").replace('"','').replace('}','').replace('manifest.f4m','playlist.m3u8').strip()
        iudy = '73776655726C3D687474703A2F2F702E6A777063646E2E636F6D2F362F31312F6A77706C617965722E666C6173682E737766207061676555726C3D687474703A2F2F6B617277616E2E7476206C6976653D31'
        if 'rtmp://' in idx[0]: idx[0] = idx[0] + ' ' + iudy.decode(md5)

    xbmcPlayer = xbmc.Player()
    listitem = xbmcgui.ListItem( idx[1], iconImage=idx[2], thumbnailImage=idx[2])
    playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
    playlist.clear()
    playlist.add(idx[0], listitem )
    xbmcPlayer.play(playlist,None,False)
    sys.exit(0)
Example #45
0
def get_status(stat):
    try:
        wert = hashlib.md5('#user='******'pass='******'loc': wert, 'la': 'AR', 'stat': str(stat)}
        r = requests.get("http://www.iptvxtra.net/xbmc/_form/rsx.php",
                         params=payload)
        urln = r.text.strip()
        if 'not allowed' in urln:
            xbmc.executebuiltin(
                'XBMC.Notification(Login Fehler , der Zugang über einen Proxy oder Tor-IPs ist nicht erlaubt ,25000,'
                + net + ')')
            sys.exit(0)
        if 'none.xml' in urln:
            xbmc.executebuiltin(
                'XBMC.Notification(Login Fehler , du bist noch nicht registriert ,25000,'
                + net + ')')
            sys.exit(0)
        if 'nonex.xml' in urln:
            xbmc.executebuiltin(
                'XBMC.Notification(Netzwerkfehler HTTP-401 , Passwort oder User ist sehr wahrscheinlich verkehrt ,25000,'
                + net + ')')
            sys.exit(0)
        if 'lockland.xml' in urln:
            xbmc.executebuiltin(
                'XBMC.Notification(Login Fehler , dieses Addon ist in deinem Land nicht verfügbar ,25000,'
                + net + ')')
            sys.exit(0)
        if 'proxy.xml' in urln:
            xbmc.executebuiltin(
                'XBMC.Notification(Login Fehler , der Zugang über einen Proxy oder Tor-IPs ist nicht erlaubt ,25000,'
                + net + ')')
            sys.exit(0)
        url = urln.split('###')
        return url[1]

    except:
        xbmc.executebuiltin(
            'XBMC.Notification(Netzwerkfehler , fehlerhafter Zugang zum Login-Server,25000,'
            + net + ')')
        sys.exit(0)
Example #46
0
    def _unshorten_linkbucks(self, uri):
        '''
        (Attempt) to decode linkbucks content. HEAVILY based on the OSS jDownloader codebase.
        This has necessidated a license change.

        '''

        r = requests.get(uri, headers=HTTP_HEADER, timeout=self._timeout)

        firstGet = time.time()

        baseloc = r.url

        if "/notfound/" in r.url or \
            "(>Link Not Found<|>The link may have been deleted by the owner|To access the content, you must complete a quick survey\.)" in r.text:
            return uri, 'Error: Link not found or requires a survey!'

        link = None

        content = r.text

        regexes = [
            r"<div id=\"lb_header\">.*?/a>.*?<a.*?href=\"(.*?)\".*?class=\"lb",
            r"AdBriteInit\(\"(.*?)\"\)",
            r"Linkbucks\.TargetUrl = '(.*?)';",
            r"Lbjs\.TargetUrl = '(http://[^<>\"]*?)'",
            r"src=\"http://static\.linkbucks\.com/tmpl/mint/img/lb\.gif\" /></a>.*?<a href=\"(.*?)\"",
            r"id=\"content\" src=\"([^\"]*)",
        ]

        for regex in regexes:
            if self.inValidate(link):
                link = find_in_text(regex, content)

        if self.inValidate(link):
            match = find_in_text(r"noresize=\"[0-9+]\" src=\"(http.*?)\"",
                                 content)
            if match:
                link = find_in_text(r"\"frame2\" frameborder.*?src=\"(.*?)\"",
                                    content)

        if self.inValidate(link):
            scripts = re.findall(
                "(<script type=\"text/javascript\">[^<]+</script>)", content)
            if not scripts:
                return uri, "No script bodies found?"

            js = False

            for script in scripts:
                # cleanup
                script = re.sub(r"[\r\n\s]+\/\/\s*[^\r\n]+", "", script)
                if re.search(
                        r"\s*var\s*f\s*=\s*window\['init'\s*\+\s*'Lb'\s*\+\s*'js'\s*\+\s*''\];[\r\n\s]+",
                        script):
                    js = script

            if not js:
                return uri, "Could not find correct script?"

            token = find_in_text(r"Token\s*:\s*'([a-f0-9]{40})'", js)
            if not token:
                token = find_in_text(r"\?t=([a-f0-9]{40})", js)

            assert token

            authKeyMatchStr = r"A(?:'\s*\+\s*')?u(?:'\s*\+\s*')?t(?:'\s*\+\s*')?h(?:'\s*\+\s*')?K(?:'\s*\+\s*')?e(?:'\s*\+\s*')?y"
            l1 = find_in_text(
                r"\s*params\['" + authKeyMatchStr + r"'\]\s*=\s*(\d+?);", js)
            l2 = find_in_text(
                r"\s*params\['" + authKeyMatchStr + r"'\]\s*=\s?params\['" +
                authKeyMatchStr + r"'\]\s*\+\s*(\d+?);", js)

            if any([not l1, not l2, not token]):
                return uri, "Missing required tokens?"

            print(l1, l2)

            authkey = int(l1) + int(l2)

            p1_url = urljoin(baseloc, "/director/?t={tok}".format(tok=token))
            print(p1_url)
            r2 = requests.get(p1_url,
                              headers=HTTP_HEADER,
                              timeout=self._timeout,
                              cookies=r.cookies)

            p1_url = urljoin(
                baseloc, "/scripts/jquery.js?r={tok}&{key}".format(tok=token,
                                                                   key=l1))
            print(p1_url)
            r2_1 = requests.get(p1_url,
                                headers=HTTP_HEADER,
                                timeout=self._timeout,
                                cookies=r.cookies)

            time_left = 5.033 - (time.time() - firstGet)
            time.sleep(max(time_left, 0))

            p3_url = urljoin(
                baseloc,
                "/intermission/loadTargetUrl?t={tok}&aK={key}&a_b=false".
                format(tok=token, key=str(authkey)))
            r3 = requests.get(p3_url,
                              headers=HTTP_HEADER,
                              timeout=self._timeout,
                              cookies=r2.cookies)

            resp_json = json.loads(r3.text)
            if "Url" in resp_json:
                return resp_json['Url'], r3.status_code

            print(p3_url)
            print(r3)
            print(r3.text)
            print(resp_json)

        return "Wat", "wat"
Example #47
0
def AutoStart():

    if __settings__.getSetting("popupx") == 'true':
        xbmc.executebuiltin(
            'XBMC.Notification(IPTVxtra , diverse Auto-Starts werden vorbereitet ,4000,'
            + icon + ')')

# ------------------------------------------------------------------------------------------------------------------------------------------- wiederherstellen der DE Settings - START
    try:
        sxUser = 0
        sxBackup = 0
        saveset = xbmc.translatePath(
            'special://userdata/addon_data/plugin.video.iptvxtra-de/backup.xml'
        )
        orgset = xbmc.translatePath(
            'special://userdata/addon_data/plugin.video.iptvxtra-de/settings.xml'
        )

        if os.path.isfile(saveset) and not os.path.isfile(orgset):
            try:
                shutil.copy(saveset, orgset)
                if __settings__.getSetting("popup") == 'true':
                    xbmc.executebuiltin(
                        'XBMC.Notification(Backup Funktion , IPTVxtra DE-Settings wurden wiederhergestellt ,5000,'
                        + icon + ')')
                print ' ------------------------------------------------------------------------------ IPTVxtra Info-Message-Service 100'
                print ' -----------------------------------------------------------------------------------------------------------------'
            except:
                pass

        try:
            fobj = open(orgset, "r")
            for line in fobj:
                if "login" in line and "xbmcuser" in line: sxUser = 1
                if "sBackup" in line and "true" in line: sxBackup = 1
            fobj.close()
        except:
            pass
        if sxBackup == 0 and sxUser == 1:
            try:
                fobj = open(saveset, "r")
                for line in fobj:
                    if "sBackup" in line and "true" in line: sxBackup = 1
                    break
                fobj.close()
            except:
                pass

        if os.path.isfile(
                saveset) and sxBackup == 1 and sxUser == 1:  # wiederherstellen
            try:
                os.remove(orgset)
            except:
                pass
            try:
                shutil.copy(saveset, orgset)
                if __settings__.getSetting("popup") == 'true':
                    xbmc.executebuiltin(
                        'XBMC.Notification(Backup Funktion , IPTVxtra-DE Settings mussten wiederhergestellt werden ,5000,'
                        + icon + ')')
                print ' ------------------------------------------------------------------------------ IPTVxtra Info-Message-Service 102'
                print ' -----------------------------------------------------------------------------------------------------------------'
            except:
                print ' ------------------------------------------------------------------------------ IPTVxtra Info-Message-Service 103'
                print ' -----------------------------------------------------------------------------------------------------------------'
    except:
        print ' ------------------------------------------------------------------------------ IPTVxtra Info-Message-Service 104'
        print ' -----------------------------------------------------------------------------------------------------------------'

# --------------------------------------------------------------------------------------------------------------------------------------------------------------   ReplayPlayer

    try:
        os.remove(record_folder + 'IPTVxtra.m3u8')
    except:
        pass
    shutil.rmtree(record_folder, ignore_errors=True)
    try:
        if len(
                filter(lambda x: x.endswith("_stream.ts"),
                       os.listdir(record_folder))) > 0:
            for i in filter(lambda x: x.endswith("_stream.ts"),
                            os.listdir(record_folder)):
                try:
                    os.remove(record_folder + i)
                except:
                    pass
    except:
        pass
    shutil.rmtree(record_folder, ignore_errors=True)

    # --------------------------------------------------------------------------------------------------------------------------------------------------------------   EcoStream updater
    if __settings__.getSetting("ecodel") == 'true':
        try:
            if os.path.isdir(eco_dir) == True:
                shutil.rmtree(eco_dir)
                print ' --------------------------------------------------------  Verzeichnis service.xbmc.ecoupd wurde gelöscht'
        except:
            print ' --------------------------------------------------------  alter EcoUpdater-Service konnte nicht gelöscht werden'
        __settings__.setSetting("ecodel", "false")

# --------------------------------------------------------------------------------------------------------------------------------------------------------------   deutsches EPG
    if __settings__.getSetting("epgde") == 'true':
        try:
            if not os.path.isfile(xmltv2de) or os.stat(xmltv2de)[8] < (
                    int(time.time()) -
                    72000) or os.path.getsize(xmltv2de) < 1200000:
                ab = requests.get('http://iptvxtra.net/xbmc/_form/session/' +
                                  xbmcaddon.Addon(
                                      id='plugin.video.iptvxtra-de').
                                  getSetting("login").strip() + '.DE')
                if str(ab.status_code) == '200':
                    if __settings__.getSetting("popup") == 'true':
                        xbmc.executebuiltin(
                            'XBMC.Notification(XMLTV , deutsches EPG File wird geladen ,4000,'
                            + iconx + ')')
                    try:
                        urllib.urlretrieve(
                            'http://srv1.iptvxtra.net/xmltv/xmltv_de_2.xmx',
                            xmltv2de)
                    except:
                        urllib.urlretrieve(
                            'http://srv3.iptvxtra.net/xmltv/xmltv_de_2.xmx',
                            xmltv2de)
                    print ' --------------------------------------------------------  DE XMLTV geladen'
        except:
            print ' --------------------------------------------------------  DE I.XMLTV konnte nicht geladen werden'

# --------------------------------------------------------------------------------------------------------------------------------------------------------------   thailändisches EPG
    if __settings__.getSetting("epgth") == 'true':
        try:
            if not os.path.isfile(xmltv2th) or os.stat(xmltv2th)[8] < (
                    int(time.time()) -
                    72000) or os.path.getsize(xmltv2th) < 1800000:
                ab = requests.get('http://iptvxtra.net/xbmc/_form/session/' +
                                  xbmcaddon.Addon(
                                      id='plugin.video.iptvxtra-th').
                                  getSetting("login").strip() + '.TH')
                if str(ab.status_code) == '200':
                    if __settings__.getSetting("popup") == 'true':
                        xbmc.executebuiltin(
                            'XBMC.Notification(XMLTV , thailaendisches EPG File wird geladen ,4000,'
                            + iconx + ')')
                    try:
                        urllib.urlretrieve(
                            'http://srv1.iptvxtra.net/xmltv/xmltv_th_2.xmx',
                            xmltv2th)
                    except:
                        urllib.urlretrieve(
                            'http://srv3.iptvxtra.net/xmltv/xmltv_th_2.xmx',
                            xmltv2th)
                    print ' --------------------------------------------------------  TH XMLTV geladen'
        except:
            print ' --------------------------------------------------------  TH XMLTV konnte nicht geladen werden'

# --------------------------------------------------------------------------------------------------------------------------------------------------------------   Programm Starter
    if __settings__.getSetting("de") == 'true':
        __settings__.setSetting("th", "false")
        __settings__.setSetting("sport", "false")
        try:
            xbmc.executebuiltin('XBMC.RunAddon(plugin.video.iptvxtra-de)')
        except:
            __settings__.setSetting("de", "false")
            print ' --------------------------------------------------------  IPTVxtra-DE nicht installiert'

    if __settings__.getSetting("th") == 'true':
        __settings__.setSetting("de", "false")
        __settings__.setSetting("sport", "false")
        try:
            xbmc.executebuiltin('XBMC.RunAddon(plugin.video.iptvxtra-th)')
        except:
            __settings__.setSetting("th", "false")
            print ' --------------------------------------------------------  IPTVxtra-TH nicht installiert'

    if __settings__.getSetting("sport") == 'true':
        __settings__.setSetting("th", "false")
        __settings__.setSetting("de", "false")
        try:
            print ' --------------------------------------------------------  Plugin s.p.o.r.t.TV'
            xbmc.executebuiltin('XBMC.RunAddon(plugin.video.s.p.o.r.t)')
        except:
            __settings__.setSetting("sport", "false")
            print ' --------------------------------------------------------  Plugin s.p.o.r.t.TV nicht installiert'

    if __settings__.getSetting("alt1") == 'true':
        try:
            print ' --------------------------------------------------------  alternatives Plugin'
            xbmc.executebuiltin('XBMC.RunAddon(' +
                                __settings__.getSetting("alt2") + ')')
        except:
            __settings__.setSetting("alt1", "false")
            print ' --------------------------------------------------------  alternatives Plugin nicht installiert'

# --------------------------------------------------------------------------------------------------------------------------------------------------------------   Player Info
    if __settings__.getSetting("playerinfox") == 'true':
        try:
            print ' --------------------------------------------------------  Playerinfo gestartet'
            if __settings__.getSetting("popup") == 'true':
                xbmc.executebuiltin(
                    'XBMC.Notification(Stream Restart , Stream-Restarter wird geladen ,4000,'
                    + iconb + ')')
            xbmc.sleep(3000)
            xbmc.executescript(
                'special://home/addons/plugin.program.iptvxtra/playerinfo.py')
        except:
            __settings__.setSetting("playerinfox", "false")
            print ' --------------------------------------------------------  Playerinfo kann nicht gestartet werden'

# --------------------------------------------------------------------------------------------------------------------------------------------------------------   EcoUpdater
    if __settings__.getSetting("eco") == 'true':
        try:
            xbmc.executebuiltin(
                'XBMC.RunPlugin(plugin://plugin.program.ecoupd)')
        except:
            __settings__.setSetting("eco", "false")
            xbmc.executebuiltin(
                'XBMC.Notification(Error EcoUpdater, der EcoUpdater ist nicht installiert ,4000,'
                + icon + ')')
            print ' --------------------------------------------------------  EcoUpdater nicht installiert'


# --------------------------------------------------------------------------------------------------------------------------------------------------------------   advancedsettings
    if __settings__.getSetting("as") == 'true':
        try:
            __settings__.setSetting("as", "false")
            xbmc.executebuiltin(
                'XBMC.Notification(advancedsettings.xml, die advancedsettings.xml wurde kopiert - beim nächsten Neustart ist diese erst aktiv ,6000,'
                + icon + ')')
        except:
            __settings__.setSetting("as", "false")
            xbmc.executebuiltin(
                'XBMC.Notification(Error advancedsettings.xml, die advancedsettings.xml wurde nicht integriert ,4000,'
                + icon + ')')
            print ' --------------------------------------------------------  advancedsettings.xml nicht installiert'
Example #48
0
def get_url(url):
        r = requests.get(url)
        return r.text
def main():
    global g_base_url, g_addon_handle, g_args, g_database_path, g_username, g_password

    kodi_init()

    debug_log_duration("PostKodiInit")

    g_database_path = os.path.join(xbmc.translatePath("special://temp/"), 'pluralsight_catalogue.db')
    xbmcplugin.setContent(g_addon_handle, 'movies')
    xbmcplugin.addSortMethod(g_addon_handle, xbmcplugin.SORT_METHOD_TITLE)
    g_username = xbmcplugin.getSetting(g_addon_handle, "username")
    g_password = xbmcplugin.getSetting(g_addon_handle, "password")

    debug_log_duration("PostSettingsLoad")

    if not credentials_are_valid():
        xbmcplugin.endOfDirectory(g_addon_handle)
    cached = g_args.get('cached', None)
    debug_log_duration("pre-cache check")
    if cached is None:
        catalogue = Catalogue.Catalogue(g_database_path)

        cache_headers = {
            "Accept-Language": "en-us",
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Accept-Encoding": "gzip",
            "If-None-Match": catalogue.etag
        }

        debug_log_duration("pre-API-get")
        r = requests.get("https://www.pluralsight.com/metadata/live/courses/", headers=cache_headers)
        debug_log_duration("post-API-get")

        if r.status_code == 304:
            debug_log_duration("Loading from cache as it has not modified (fast-path)")
        else:
            debug_log_duration("Re-priming DB from the API response (slow-path)")
            data_etag = ""
            if "ETag" in r.headers:
                data_etag = r.headers["ETag"]
            catalogue.update(data_etag, r.json())

    else:
        catalogue = Catalogue.Catalogue(g_database_path)

    debug_log_duration("catalogue-loaded")
    mode = g_args.get('mode', None)

    if mode is None:
        default_view()
    elif mode[0] == MODE_COURSES:
        courses_view(catalogue.courses)
    elif mode[0] == MODE_NEW_COURSES:
        courses_view(catalogue.new_courses)
    elif mode[0] == MODE_COURSE_BY_AUTHOR:
        course_by_author_view(catalogue)
    elif mode[0] == MODE_AUTHORS:
        author_view(catalogue)
    elif mode[0] == MODE_MODULES:
        module_view(catalogue)
    elif mode[0] == MODE_CATEGORY:
        category_view(catalogue)
    elif mode[0] == MODE_COURSE_BY_CATEGORY:
        category_id = g_args.get('category_id', None)[0]
        courses_view(catalogue.get_courses_by_category_id(category_id))
    elif mode[0] == MODE_CLIPS:
        clip_view(catalogue)
    elif mode[0] == MODE_SEARCH_HISTORY:
        search_history_view(catalogue)
    elif mode[0] == MODE_SEARCH:
        search_view(catalogue)
    elif mode[0] == MODE_FAVOURITES:
        favourites_view(catalogue)
    elif mode[0] == MODE_RANDOM:
        random_view(catalogue)
    elif mode[0] == MODE_PLAY:
        play_view(catalogue)
    elif mode[0] == MODE_BOOKMARKS:
        bookmarks_view(catalogue)
    elif mode[0] == MODE_RECENT:
        recent_view(catalogue)

    debug_log_duration("closing catalogue")
    catalogue.close_db()
    xbmcplugin.endOfDirectory(g_addon_handle)
Example #50
0
def AutoStart():

    if __settings__.getSetting("popupx") == 'true':
        xbmc.executebuiltin('XBMC.Notification(IPTVxtra , diverse Auto-Starts werden vorbereitet ,4000,'+icon+')')


# ------------------------------------------------------------------------------------------------------------------------------------------- wiederherstellen der DE Settings - START
    try:
        sxUser = 0
        sxBackup = 0
        saveset = xbmc.translatePath('special://userdata/addon_data/plugin.video.iptvxtra-de/backup.xml')
        orgset = xbmc.translatePath('special://userdata/addon_data/plugin.video.iptvxtra-de/settings.xml')

        if os.path.isfile(saveset) and not os.path.isfile(orgset):
            try:
                shutil.copy(saveset, orgset)
                if __settings__.getSetting("popup") == 'true': xbmc.executebuiltin('XBMC.Notification(Backup Funktion , IPTVxtra DE-Settings wurden wiederhergestellt ,5000,'+icon+')')
                print ' ------------------------------------------------------------------------------ IPTVxtra Info-Message-Service 100'
                print ' -----------------------------------------------------------------------------------------------------------------'
            except: pass

        try:
            fobj = open(orgset, "r") 
            for line in fobj:
                if "login" in line and "xbmcuser" in line: sxUser = 1
                if "sBackup" in line and "true" in line: sxBackup = 1
            fobj.close()
        except: pass
        if sxBackup == 0 and sxUser == 1:
            try:
                fobj = open(saveset, "r") 
                for line in fobj:
                    if "sBackup" in line and "true" in line: sxBackup = 1
                    break
                fobj.close()
            except: pass

        if os.path.isfile(saveset) and sxBackup == 1 and sxUser == 1:        # wiederherstellen  
            try: os.remove(orgset)
            except: pass
            try: 
                shutil.copy(saveset, orgset)
                if __settings__.getSetting("popup") == 'true': xbmc.executebuiltin('XBMC.Notification(Backup Funktion , IPTVxtra-DE Settings mussten wiederhergestellt werden ,5000,'+icon+')')
                print ' ------------------------------------------------------------------------------ IPTVxtra Info-Message-Service 102'
                print ' -----------------------------------------------------------------------------------------------------------------'
            except:
                print ' ------------------------------------------------------------------------------ IPTVxtra Info-Message-Service 103'
                print ' -----------------------------------------------------------------------------------------------------------------'
    except: 
        print ' ------------------------------------------------------------------------------ IPTVxtra Info-Message-Service 104'
        print ' -----------------------------------------------------------------------------------------------------------------'

# --------------------------------------------------------------------------------------------------------------------------------------------------------------   ReplayPlayer

    try: os.remove(record_folder + 'IPTVxtra.m3u8')
    except: pass
    shutil.rmtree(record_folder, ignore_errors=True)
    try:
        if len(filter(lambda x: x.endswith("_stream.ts"), os.listdir(record_folder))) > 0:
            for i in filter(lambda x: x.endswith("_stream.ts"), os.listdir(record_folder)):
                try: os.remove(record_folder + i)
                except: pass
    except: pass
    shutil.rmtree(record_folder, ignore_errors=True)

# --------------------------------------------------------------------------------------------------------------------------------------------------------------   EcoStream updater
    if __settings__.getSetting("ecodel") == 'true':
        try:
            if os.path.isdir(eco_dir) == True:
                shutil.rmtree(eco_dir)
                print ' --------------------------------------------------------  Verzeichnis service.xbmc.ecoupd wurde gelöscht'
        except:
            print ' --------------------------------------------------------  alter EcoUpdater-Service konnte nicht gelöscht werden'
        __settings__.setSetting("ecodel", "false")

# --------------------------------------------------------------------------------------------------------------------------------------------------------------   deutsches EPG
    if __settings__.getSetting("epgde") == 'true':
        try:
            if not os.path.isfile(xmltv2de) or os.stat(xmltv2de)[8] < (int(time.time()) - 72000) or os.path.getsize(xmltv2de) < 1200000:
                ab = requests.get('http://iptvxtra.net/xbmc/_form/session/' + xbmcaddon.Addon(id = 'plugin.video.iptvxtra-de').getSetting("login").strip() + '.DE')
                if str(ab.status_code) == '200':
                    if __settings__.getSetting("popup") == 'true':
                        xbmc.executebuiltin('XBMC.Notification(XMLTV , deutsches EPG File wird geladen ,4000,'+iconx+')')
                    try: urllib.urlretrieve('http://srv1.iptvxtra.net/xmltv/xmltv_de_2.xmx', xmltv2de)
                    except: urllib.urlretrieve('http://srv3.iptvxtra.net/xmltv/xmltv_de_2.xmx', xmltv2de)
                    print ' --------------------------------------------------------  DE XMLTV geladen'
        except:
            print ' --------------------------------------------------------  DE I.XMLTV konnte nicht geladen werden'

# --------------------------------------------------------------------------------------------------------------------------------------------------------------   thailändisches EPG
    if __settings__.getSetting("epgth") == 'true':
        try:
            if not os.path.isfile(xmltv2th) or os.stat(xmltv2th)[8] < (int(time.time()) - 72000) or os.path.getsize(xmltv2th) < 1800000:
                ab = requests.get('http://iptvxtra.net/xbmc/_form/session/' + xbmcaddon.Addon(id = 'plugin.video.iptvxtra-th').getSetting("login").strip() + '.TH')
                if str(ab.status_code) == '200':
                        if __settings__.getSetting("popup") == 'true':
                            xbmc.executebuiltin('XBMC.Notification(XMLTV , thailaendisches EPG File wird geladen ,4000,'+iconx+')')
                        try: urllib.urlretrieve('http://srv1.iptvxtra.net/xmltv/xmltv_th_2.xmx', xmltv2th)
                        except: urllib.urlretrieve('http://srv3.iptvxtra.net/xmltv/xmltv_th_2.xmx', xmltv2th)
                        print ' --------------------------------------------------------  TH XMLTV geladen'
        except:
            print ' --------------------------------------------------------  TH XMLTV konnte nicht geladen werden'

# --------------------------------------------------------------------------------------------------------------------------------------------------------------   Programm Starter
    if __settings__.getSetting("de") == 'true':
        __settings__.setSetting("th", "false")
        __settings__.setSetting("sport", "false")
        try:
            xbmc.executebuiltin('XBMC.RunAddon(plugin.video.iptvxtra-de)')
        except:
            __settings__.setSetting("de", "false")
            print ' --------------------------------------------------------  IPTVxtra-DE nicht installiert'

    if __settings__.getSetting("th") == 'true':
        __settings__.setSetting("de", "false")
        __settings__.setSetting("sport", "false")
        try:
            xbmc.executebuiltin('XBMC.RunAddon(plugin.video.iptvxtra-th)')
        except:
            __settings__.setSetting("th", "false")
            print ' --------------------------------------------------------  IPTVxtra-TH nicht installiert'

    if __settings__.getSetting("sport") == 'true':
        __settings__.setSetting("th", "false")
        __settings__.setSetting("de", "false")
        try:
            print ' --------------------------------------------------------  Plugin s.p.o.r.t.TV'
            xbmc.executebuiltin('XBMC.RunAddon(plugin.video.s.p.o.r.t)')
        except:
            __settings__.setSetting("sport", "false")
            print ' --------------------------------------------------------  Plugin s.p.o.r.t.TV nicht installiert'

    if __settings__.getSetting("alt1") == 'true':
        try:
            print ' --------------------------------------------------------  alternatives Plugin'
            xbmc.executebuiltin('XBMC.RunAddon('+ __settings__.getSetting("alt2")+')')
        except:
            __settings__.setSetting("alt1", "false")
            print ' --------------------------------------------------------  alternatives Plugin nicht installiert'

# --------------------------------------------------------------------------------------------------------------------------------------------------------------   Player Info
    if __settings__.getSetting("playerinfox") == 'true':
        try:
            print ' --------------------------------------------------------  Playerinfo gestartet'
            if __settings__.getSetting("popup") == 'true':
                xbmc.executebuiltin('XBMC.Notification(Stream Restart , Stream-Restarter wird geladen ,4000,'+iconb+')')
            xbmc.sleep(3000)
            xbmc.executescript('special://home/addons/plugin.program.iptvxtra/playerinfo.py')
        except:
            __settings__.setSetting("playerinfox", "false")
            print ' --------------------------------------------------------  Playerinfo kann nicht gestartet werden'

# --------------------------------------------------------------------------------------------------------------------------------------------------------------   EcoUpdater
    if __settings__.getSetting("eco") == 'true':
        try:
            xbmc.executebuiltin('XBMC.RunPlugin(plugin://plugin.program.ecoupd)')
        except:
            __settings__.setSetting("eco", "false")
            xbmc.executebuiltin('XBMC.Notification(Error EcoUpdater, der EcoUpdater ist nicht installiert ,4000,'+icon+')')
            print ' --------------------------------------------------------  EcoUpdater nicht installiert'

# --------------------------------------------------------------------------------------------------------------------------------------------------------------   advancedsettings
    if __settings__.getSetting("as") == 'true':
        try:
            __settings__.setSetting("as", "false")
            xbmc.executebuiltin('XBMC.Notification(advancedsettings.xml, die advancedsettings.xml wurde kopiert - beim nächsten Neustart ist diese erst aktiv ,6000,'+icon+')')
        except:
            __settings__.setSetting("as", "false")
            xbmc.executebuiltin('XBMC.Notification(Error advancedsettings.xml, die advancedsettings.xml wurde nicht integriert ,4000,'+icon+')')
            print ' --------------------------------------------------------  advancedsettings.xml nicht installiert'
Example #51
0
def get_url(url):
    r = requests.get(url)
    return r.text
def main():
    global g_base_url, g_addon_handle, g_args, g_database_path, g_username, g_password

    kodi_init()

    debug_log_duration("PostKodiInit")

    g_database_path = os.path.join(xbmc.translatePath("special://temp/"), 'pluralsight_catalogue.db')
    xbmcplugin.setContent(g_addon_handle, 'movies')
    xbmcplugin.addSortMethod(g_addon_handle, xbmcplugin.SORT_METHOD_TITLE)
    g_username = xbmcplugin.getSetting(g_addon_handle, "username")
    g_password = xbmcplugin.getSetting(g_addon_handle, "password")

    debug_log_duration("PostSettingsLoad")

    if not credentials_are_valid():
        xbmcplugin.endOfDirectory(g_addon_handle)
    cached = g_args.get('cached', None)
    debug_log_duration("pre-cache check")
    if cached is None:
        catalogue = Catalogue.Catalogue(g_database_path)

        cache_headers = {
            "Accept-Language": "en-us",
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Accept-Encoding": "gzip",
            "If-None-Match": catalogue.etag
        }

        debug_log_duration("pre-API-get")
        r = requests.get("http://www.pluralsight.com/metadata/live/courses/", headers=cache_headers)
        debug_log_duration("post-API-get")

        if r.status_code == 304:
            debug_log_duration("Loading from cache as it has not modified (fast-path)")
        else:
            debug_log_duration("Re-priming DB from the API response (slow-path)")
            catalogue.update(r.headers["ETag"], r.json())

    else:
        catalogue = Catalogue.Catalogue(g_database_path)

    debug_log_duration("catalogue-loaded")
    mode = g_args.get('mode', None)

    if mode is None:
        default_view()
    elif mode[0] == MODE_COURSES:
        courses_view(catalogue.courses)
    elif mode[0] == MODE_NEW_COURSES:
        courses_view(catalogue.new_courses)
    elif mode[0] == MODE_COURSE_BY_AUTHOR:
        course_by_author_view(catalogue)
    elif mode[0] == MODE_AUTHORS:
        author_view(catalogue)
    elif mode[0] == MODE_MODULES:
        module_view(catalogue)
    elif mode[0] == MODE_CATEGORY:
        category_view(catalogue)
    elif mode[0] == MODE_COURSE_BY_CATEGORY:
        category_id = g_args.get('category_id', None)[0]
        courses_view(catalogue.get_courses_by_category_id(category_id))
    elif mode[0] == MODE_CLIPS:
        clip_view(catalogue)
    elif mode[0] == MODE_SEARCH_HISTORY:
        search_history_view(catalogue)
    elif mode[0] == MODE_SEARCH:
        search_view(catalogue)
    elif mode[0] == MODE_FAVOURITES:
        favourites_view(catalogue)
    elif mode[0] == MODE_RANDOM:
        random_view(catalogue)
    elif mode[0] == MODE_PLAY:
        play_view(catalogue)
    elif mode[0] == MODE_BOOKMARKS:
        bookmarks_view(catalogue)
    elif mode[0] == MODE_RECENT:
        recent_view(catalogue)

    debug_log_duration("closing catalogue")
    catalogue.close_db()
    xbmcplugin.endOfDirectory(g_addon_handle)