Esempio n. 1
0
 def clearCache(self):
     control.idle()
     yes = control.yesnoDialog(control.lang(32056).encode('utf-8'), '', '')
     if not yes: return
     from resources.lib.modules import cache
     cache.cache_clear()
     control.infoDialog(control.lang(32057).encode('utf-8'), sound=True, icon='INFO')
Esempio n. 2
0
				def dialog(url):
					# [BUBBLESCODE]
					#try: self.disableScraper = control.yesnoDialog('Torba requires you visit, on any device, the following url to watch this video:', '[COLOR skyblue]%s[/COLOR]' % url, '', 'Torba', 'Cancel', 'Settings')
					#except: pass
					if not internal:
						try: self.disableScraper = control.yesnoDialog('Torba requires you visit, on any device, the following url to watch this video:', '[COLOR skyblue]%s[/COLOR]' % url, '', 'Torba', 'Cancel', 'Settings')
						except: pass
Esempio n. 3
0
def clear(table=None):
    try:
        control.idle()

        if table == None: table = ['rel_list', 'rel_lib']
        elif not type(table) == list: table = [table]

        yes = control.yesnoDialog(control.lang(30401).encode('utf-8'), '', '')
        if not yes: return

        dbcon = database.connect(control.cacheFile)
        dbcur = dbcon.cursor()

        for t in table:
            try:
                dbcur.execute("DROP TABLE IF EXISTS %s" % t)
                dbcur.execute("VACUUM")
                dbcon.commit()
            except:
                pass
    except:
        pass

    import xbmcgui
    xbmcgui.Dialog().notification('[COLOR ffff0000]StreamHub[/COLOR]','Process Complete')
Esempio n. 4
0
def clear(table=None):
    try:
        control.idle()

        if table == None: table = ['rel_list', 'rel_lib']
        elif not type(table) == list: table = [table]

        yes = control.yesnoDialog('Are You Sure?', '', '')
        if not yes: return

        dbcon = database.connect(control.cacheFile)
        dbcur = dbcon.cursor()

        for t in table:
            try:
                dbcur.execute("DROP TABLE IF EXISTS %s" % t)
                dbcur.execute("VACUUM")
                dbcon.commit()
            except:
                pass

        control.infoDialog('Cache.db Cleared')
        xbmc.executebuiltin('Container.Refresh()')
    except:
        pass
Esempio n. 5
0
    def get(self, name, year='0'):
        try:
            offset = '0'

            if not control.setting('bookmarks') == 'true': raise Exception()

            idFile = hashlib.md5()
            for i in name: idFile.update(str(i))
            for i in year: idFile.update(str(i))
            idFile = str(idFile.hexdigest())

            dbcon = database.connect(control.bookmarksFile)
            dbcur = dbcon.cursor()
            dbcur.execute("SELECT * FROM bookmark WHERE idFile = '%s'" % idFile)
            match = dbcur.fetchone()
            self.offset = str(match[1])
            dbcon.commit()

            if self.offset == '0': raise Exception()

            minutes, seconds = divmod(float(self.offset), 60) ; hours, minutes = divmod(minutes, 60)
            label = '%02d:%02d:%02d' % (hours, minutes, seconds)
            label = (control.lang(32502) % label).encode('utf-8')

            try: yes = control.dialog.contextmenu([label, control.lang(32501).encode('utf-8'), ])
            except: yes = control.yesnoDialog(label, '', '', str(name), control.lang(32503).encode('utf-8'), control.lang(32501).encode('utf-8'))

            if yes: self.offset = '0'

            return self.offset
        except:
            return offset
Esempio n. 6
0
def clear(table=None):
    try:
        control.idle()

        if table == None: table = ['rel_list', 'rel_lib']
        elif not type(table) == list: table = [table]

        yes = control.yesnoDialog(control.lang(30401).encode('utf-8'), '', '')
        if not yes: return

        dbcon = database.connect(control.cacheFile)
        dbcur = dbcon.cursor()

        for t in table:
            try:
                dbcur.execute("DROP TABLE IF EXISTS %s" % t)
                dbcur.execute("VACUUM")
                dbcon.commit()
            except:
                pass

        nanscrapers.clear_cache()

        control.infoDialog(control.lang(30402).encode('utf-8'))
    except:
        pass
Esempio n. 7
0
    def range(self, url):
        control.idle()

        yes = control.yesnoDialog(control.lang(30425).encode("utf-8"), "", "")
        if not yes:
            return

        if not control.condVisibility("Window.IsVisible(infodialog)") and not control.condVisibility("Player.HasVideo"):
            control.infoDialog(control.lang(30421).encode("utf-8"), time=10000000)
            self.infoDialog = True

        from resources.lib.indexers import movies

        items = movies.movies().get(url, idx=False)
        if items == None:
            items = []

        for i in items:
            try:
                if xbmc.abortRequested == True:
                    return sys.exit()
                self.add(i["name"], i["title"], i["year"], i["imdb"], range=True)
            except:
                pass

        if self.infoDialog == True:
            control.infoDialog(control.lang(30423).encode("utf-8"), time=1)

        if self.library_setting == "true" and not control.condVisibility("Library.IsScanningVideo"):
            control.execute("UpdateLibrary(video)")
Esempio n. 8
0
    def range(self, url):
        control.idle()

        yes = control.yesnoDialog(control.lang(32555).encode('utf-8'), '', '')
        if not yes: return

        if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'):
            control.infoDialog(control.lang(32552).encode('utf-8'), time=10000000)
            self.infoDialog = True

        from resources.lib.indexers import tvshows
        items = tvshows.tvshows().get(url, idx=False)
        if items == None: items = []

        for i in items:
            try:
                if xbmc.abortRequested == True: return sys.exit()
                self.add(i['title'], i['year'], i['imdb'], i['tvdb'], range=True)
            except:
                pass

        if self.infoDialog == True:
            control.infoDialog(control.lang(32554).encode('utf-8'), time=1)

        if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo'):
            control.execute('UpdateLibrary(video)')
Esempio n. 9
0
def rdAuthorize():
    try:
        CLIENT_ID = 'X245A4XAIBGVM'
        USER_AGENT = 'Kodi Exodus/3.0'

        if not '' in credentials()['realdebrid'].values():
            if control.yesnoDialog(control.lang(30411).encode('utf-8'), control.lang(30413).encode('utf-8'), '', 'RealDebrid', control.lang(30415).encode('utf-8'), control.lang(30414).encode('utf-8')):
                control.setSetting(id='realdebrid.id', value='')
                control.setSetting(id='realdebrid.secret', value='')
                control.setSetting(id='realdebrid.token', value='')
                control.setSetting(id='realdebrid.refresh', value='')
                control.setSetting(id='realdebrid.auth', value='')
            raise Exception()

        headers = {'User-Agent': USER_AGENT}
        url = 'https://api.real-debrid.com/oauth/v2/device/code?client_id=%s&new_credentials=yes' % (CLIENT_ID)
        result = client.request(url, headers=headers)
        result = json.loads(result)
        verification_url = (control.lang(30416) + '[COLOR skyblue]%s[/COLOR]' % result['verification_url']).encode('utf-8')
        user_code = (control.lang(30417) + '[COLOR skyblue]%s[/COLOR]' % result['user_code']).encode('utf-8')
        device_code = result['device_code']
        interval = result['interval']

        progressDialog = control.progressDialog
        progressDialog.create('RealDebrid', verification_url, user_code)

        for i in range(0, 3600):
            try:
                if progressDialog.iscanceled(): break
                time.sleep(1)
                if not float(i) % interval == 0: raise Exception()
                url = 'https://api.real-debrid.com/oauth/v2/device/credentials?client_id=%s&code=%s' % (CLIENT_ID, device_code)
                result = client.request(url, headers=headers, error=True)
                result = json.loads(result)
                if 'client_secret' in result: break
            except:
                pass

        try: progressDialog.close()
        except: pass

        id, secret = result['client_id'], result['client_secret'] 

        url = 'https://api.real-debrid.com/oauth/v2/token'
        post = urllib.urlencode({'client_id': id, 'client_secret': secret, 'code': device_code, 'grant_type': 'http://oauth.net/grant_type/device/1.0'})

        result = client.request(url, post=post, headers=headers)
        result = json.loads(result)

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

        control.setSetting(id='realdebrid.id', value=id)
        control.setSetting(id='realdebrid.secret', value=secret)
        control.setSetting(id='realdebrid.token', value=token)
        control.setSetting(id='realdebrid.refresh', value=refresh)
        control.setSetting(id='realdebrid.auth', value='*************')
        raise Exception()
    except:
        control.openSettings('3.13')
Esempio n. 10
0
def addDownload(name, url, image, resolved=False):
    if resolved:
        resolved = url
    try:
        def download(): return []
        result = cache.get(download, 600000000, table='rel_dl')
        result = [i['name'] for i in result]
    except:
        pass

    if name in result:
        return control.infoDialog('Stavka je već dodana u red čekanja', name)

    try:
        if not resolved:
            import urlresolver
            resolved = urlresolver.resolve(url)
    except:
        return control.infoDialog('Unplayable stream')
        pass

    try:
        u = resolved.split('|')[0]
        try: headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1]))
        except: headers = dict('')

        ext = os.path.splitext(urlparse.urlparse(u).path)[1][1:].lower()
        if ext == 'm3u8': raise Exception()
        #if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4'
        try:    name = name.decode('utf-8')
        except: pass
        name=re.sub('[^-a-zA-Z0-9_.() ]+', '', name)
        name=name.rstrip('.')
        dest = name + '.' + ext

        req = urllib2.Request(u, headers=headers)
        resp = urllib2.urlopen(req, timeout=30)
        size = int(resp.headers['Content-Length'])
        size = ' %.2f GB' % (float(size) / 1073741824)

        no = control.yesnoDialog(dest, 'Veličina datoteke je ' + size, 'Nastaviti s preuzimanjem?', name + ' - ' + 'Potvrdi preuzimanje', 'Potvrdi', 'Prekini')

        if no: return
    except:
        return control.infoDialog('Nije moguće preuzeti')
        pass

    def download(): return [{'name': name, 'url': url, 'image': image}]
    result = cache.get(download, 600000000, table='rel_dl')
    result = [i for i in result if not i['url'] == url]
    def download(): return result + [{'name': name, 'url': url, 'image': image}]
    result = cache.get(download, 0, table='rel_dl')

    control.infoDialog('Datoteka dodana u red čekanja', name)
Esempio n. 11
0
    def getBookmark(self):
        try:
            if not control.setting('bookmarks') == 'true': raise Exception()

            self.offset = bookmarks.getBookmark(self.name, self.year)
            if self.offset == '0': raise Exception()

            minutes, seconds = divmod(float(self.offset), 60) ; hours, minutes = divmod(minutes, 60)
            yes = control.yesnoDialog('%s %02d:%02d:%02d' % (control.lang(30461).encode('utf-8'), hours, minutes, seconds), '', '', self.name, control.lang(30463).encode('utf-8'), control.lang(30462).encode('utf-8'))

            if yes: self.offset = '0'
        except:
            pass
Esempio n. 12
0
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog(control.lang(30479).encode('utf-8'), control.lang(30481).encode('utf-8'), '', 'Trakt', control.lang(30483).encode('utf-8'), control.lang(30482).encode('utf-8')):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        if control.yesnoDialog(control.lang(30484).encode('utf-8') + '[COLOR skyblue]http://trakt.tv/pin/7920[/COLOR]', control.lang(30485).encode('utf-8'), control.lang(30486).encode('utf-8'), 'Trakt', control.lang(30487).encode('utf-8'), control.lang(30488).encode('utf-8')): raise Exception()

        k = control.keyboard('', control.lang(30487).encode('utf-8'))
        k.doModal() ; pin = k.getText() if k.isConfirmed() else None
        if pin == '' or pin == None: raise Exception()

        trakt_base = 'http://api-v2launch.trakt.tv'

        headers = {'Content-Type': 'application/json', 'trakt-api-key': 'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa', 'trakt-api-version': '2'}

        post = {'client_id': 'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa', 'client_secret': '90a1840447a1e39d350023263902fe7010338d19789e6260f18df56a8b07a68a', 'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob', 'grant_type': 'authorization_code', 'code': pin}

        result = client.request(urlparse.urljoin(trakt_base, '/oauth/token'), post=json.dumps(post), headers=headers)
        result = json.loads(result)

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

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

        result = client.request(urlparse.urljoin(trakt_base, '/users/me'), headers=headers)
        result = json.loads(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('3.1')
Esempio n. 13
0
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog('An account already exists.', 'Do you want to reset?', '', 'Trakt'):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        result = getTrakt('/oauth/device/code', {'client_id': '3b76e1b99fa4a5b27f63e04307754751514d88916195ea8abc1c48eeef68f0d9'})
        result = json.loads(result)
        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 = control.progressDialog
        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 = getTrakt('/oauth/device/token', {'client_id': '3b76e1b99fa4a5b27f63e04307754751514d88916195ea8abc1c48eeef68f0d9', 'client_secret': 'b0be7e72b647bcb44f2846b29729028e5d75fa710b91812027ae79cc48456a16', 'code': device_code})
                r = json.loads(r)
                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': '3b76e1b99fa4a5b27f63e04307754751514d88916195ea8abc1c48eeef68f0d9', 'trakt-api-version': '2', 'Authorization': 'Bearer %s' % token}

        result = client.request('http://api-v2launch.trakt.tv/users/me', headers=headers)
        result = json.loads(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('0.1')
Esempio n. 14
0
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog(control.lang(30479).encode('utf-8'), control.lang(30481).encode('utf-8'), '', 'Trakt', control.lang(30483).encode('utf-8'), control.lang(30482).encode('utf-8')):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        result = getTrakt('/oauth/device/code', {'client_id': 'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa'})
        result = json.loads(result)
        verification_url = (control.lang(30416) + '[COLOR skyblue]%s[/COLOR]' % result['verification_url']).encode('utf-8')
        user_code = (control.lang(30417) + '[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 = control.progressDialog
        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 = getTrakt('/oauth/device/token', {'client_id': 'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa', 'client_secret': '90a1840447a1e39d350023263902fe7010338d19789e6260f18df56a8b07a68a', 'code': device_code})
                r = json.loads(r)
                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': 'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa', 'trakt-api-version': '2', 'Authorization': 'Bearer %s' % token}

        result = client.request('http://api-v2launch.trakt.tv/users/me', headers=headers)
        result = json.loads(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('3.1')
Esempio n. 15
0
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog(control.lang(32511).encode('utf-8'), control.lang(32512).encode('utf-8'), '', 'Trakt'):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        result = getTraktAsJson('/oauth/device/code', {'client_id': V2_API_KEY})
        verification_url = (control.lang(32513) % result['verification_url']).encode('utf-8')
        user_code = (control.lang(32514) % result['user_code']).encode('utf-8')
        expires_in = int(result['expires_in'])
        device_code = result['device_code']
        interval = result['interval']

        progressDialog = control.progressDialog
        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})
                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 = client.request(urlparse.urljoin(BASE_URL, '/users/me'), headers=headers)
        result = utils.json_loads_as_str(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('3.1')
def addDownload(name, url, image, provider=None):
    try:
        def download(): return []
        result = cache.bennu_download_get(download, 600000000, table='rel_dl')
        result = [i['name'] for i in result]
    except:
        pass

    try:
        if name in result:
            return control.infoDialog('Item Already In Your Queue', name)
    except: 
        pass
        
    from resources.lib.indexers import bennustreams
    url = bennustreams.resolver().link(url)
    if url == None: return

    try:
        u = url.split('|')[0]
        try: headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1]))
        except: headers = dict('')

        ext = os.path.splitext(urlparse.urlparse(u).path)[1][1:].lower()
        if ext == 'm3u8': raise Exception()
        if not ext in ['mp4', 'm4a', 'mp3', 'aac', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4'
        dest = name + '.' + ext

        req = urllib2.Request(u, headers=headers)
        resp = urllib2.urlopen(req, timeout=30)
        size = int(resp.headers['Content-Length'])
        size = ' %.2f GB' % (float(size) / 1073741824)

        no = control.yesnoDialog(dest, 'Complete file is' + size, 'Continue with download?', name + ' - ' + 'Confirm Download', 'Confirm', 'Cancel')

        if no: return
    except:
        return control.infoDialog('Unable to download')
        pass

    def download(): return [{'name': name, 'url': url, 'image': image}]
    result = cache.bennu_download_get(download, 600000000, table='rel_dl')
    result = [i for i in result if not i['url'] == url]
    def download(): return result + [{'name': name, 'url': url, 'image': image}]
    result = cache.bennu_download_get(download, 0, table='rel_dl')

    control.infoDialog('Item Added to Queue', name)
Esempio n. 17
0
    def clearSources(self):
        try:
            control.idle()

            yes = control.yesnoDialog(control.lang(30510).encode('utf-8'), '', '')
            if not yes: return

            control.makeFile(control.dataPath)
            dbcon = database.connect(control.providercacheFile)
            dbcur = dbcon.cursor()
            dbcur.execute("DROP TABLE IF EXISTS rel_src")
            dbcur.execute("VACUUM")
            dbcon.commit()

            control.infoDialog(control.lang(30511).encode('utf-8'))
        except:
            pass
Esempio n. 18
0
                'No backup location found: Please setup your Backup location in the addon settings',
                '', '')
            xbmc.executebuiltin('RunPlugin(%s?action=openSettings&query=7.0)' %
                                sys.argv[0])
elif action == 'calendar':
    episodes.episodes().calendar(url)
elif action == 'calendars':
    episodes.episodes().calendars()
elif action == 'channels':
    channels.channels().get()
elif action == 'clearCache':
    navigator.navigator().clearCache()
elif action == 'clearProgress':
    progressFile = os.path.join(datapath, 'progress.db')
    if os.path.exists(progressFile):
        if control.yesnoDialog(control.lang(32056).encode('utf-8'), '', ''):
            try:
                os.remove(progressFile)
                dialog.ok('Clear Progress', 'Clear Progress Complete', '', '')
            except:
                dialog.ok('Clear Progress',
                          'There was an error Deleting the Database', '', '')
    else:
        control.infoDialog(control.lang2(161).encode('utf-8'),
                           heading='"Progress Database"',
                           sound=False,
                           icon=thumbnail)
elif action == 'clearSources':
    import universalscrapers
    universalscrapers.clear_cache()
elif action == 'deleteFavourite':
Esempio n. 19
0
    def get(self, name, season, episode, imdb, year='0'):
        offset = '0'

        if control.setting('bookmarks') == 'true':
            if control.setting('bookmarks.trakt') == 'true':
                try:
                    from resources.lib.modules import trakt

                    if not episode is None:

                        # Looking for a Episode progress

                        traktInfo = trakt.getTraktAsJson('https://api.trakt.tv/sync/playback/episodes?extended=full')
                        for i in traktInfo:
                            if imdb == i['show']['ids']['imdb']:
                                # Checking Episode Number
                                if int(season) == i['episode']['season'] and int(episode) == i['episode']['number']:
                                    # Calculating Offset to seconds
                                    offset = (float(i['progress'] / 100) * int(i['episode']['runtime']) * 60)
                    else:

                        # Looking for a Movie Progress
                        traktInfo = trakt.getTraktAsJson('https://api.trakt.tv/sync/playback/episodes?extended=full')
                        for i in traktInfo:
                            if imdb == i['movie']['ids']['imdb']:
                                # Calculating Offset to seconds
                                offset = (float(i['progress'] / 100) * int(i['movie']['runtime']) * 60)

                    if control.setting('bookmarks.auto') == 'false':
                        try:
                            yes = control.dialog.contextmenu(["Resume", control.lang(32501).encode('utf-8'), ])
                        except:
                            yes = control.yesnoDialog("Resume", '', '', str(name), control.lang(32503).encode('utf-8'),
                                                      control.lang(32501).encode('utf-8'))
                        if yes: offset = '0'

                    return offset

                except:
                    return '0'
            else:
                try:
                    offset = '0'

                    if not control.setting('bookmarks') == 'true': raise Exception()

                    idFile = hashlib.md5()
                    for i in name: idFile.update(str(i))
                    for i in year: idFile.update(str(i))
                    idFile = str(idFile.hexdigest())

                    dbcon = database.connect(control.bookmarksFile)
                    dbcur = dbcon.cursor()
                    dbcur.execute("SELECT * FROM bookmark WHERE idFile = '%s'" % idFile)
                    match = dbcur.fetchone()
                    self.offset = str(match[1])
                    dbcon.commit()
                    if self.offset == '0': raise Exception()

                    minutes, seconds = divmod(float(self.offset), 60);
                    hours, minutes = divmod(minutes, 60)
                    label = '%02d:%02d:%02d' % (hours, minutes, seconds)
                    label = (control.lang(32502) % label).encode('utf-8')

                    if control.setting('bookmarks.auto') == 'false':

                        try:
                            yes = control.dialog.contextmenu([label, control.lang(32501).encode('utf-8'), ])
                        except:
                            yes = control.yesnoDialog(label, '', '', str(name), control.lang(32503).encode('utf-8'),
                                                      control.lang(32501).encode('utf-8'))
                        if yes: self.offset = '0'

                    return self.offset
                except:
                    return offset
        else:
            return offset
Esempio n. 20
0
 def clearCacheSearch(self):
     control.idle()
     if control.yesnoDialog(control.lang(32056).encode('utf-8'), '', ''):
         control.setSetting('tvsearch', '')
         control.setSetting('moviesearch', '')
         control.refresh()
Esempio n. 21
0
 def dialog(url):
     try: self.disableScraper = control.yesnoDialog('Torba requires you visit, on any device, the following url to watch this video:', '[COLOR skyblue]%s[/COLOR]' % url, '', 'Torba', 'Cancel', 'Settings')
     except: pass
Esempio n. 22
0
 def clearCacheAll(self):
     control.idle()
     yes = control.yesnoDialog("Sind Sie sicher?", '', '')
     if not yes: return
     cache.cache_clear_all()
     control.infoDialog("Vorgang abgeschlossen", sound=True, icon='INFO')
Esempio n. 23
0
    def get(self, name, season, episode, imdb, year='0'):
        offset = '0'

        if control.setting('bookmarks') == 'true':
            if control.setting('bookmarks.trakt') == 'true':
                try:
                    from resources.lib.modules import trakt

                    if not episode is None:

                        # Looking for a Episode progress

                        traktInfo = trakt.getTraktAsJson(
                            'https://api.trakt.tv/sync/playback/episodes?extended=full'
                        )
                        for i in traktInfo:
                            if imdb == i['show']['ids']['imdb']:
                                # Checking Episode Number
                                if int(season
                                       ) == i['episode']['season'] and int(
                                           episode) == i['episode']['number']:
                                    # Calculating Offset to seconds
                                    offset = (float(i['progress'] / 100) *
                                              int(i['episode']['runtime']) *
                                              60)
                    else:

                        # Looking for a Movie Progress
                        traktInfo = trakt.getTraktAsJson(
                            'https://api.trakt.tv/sync/playback/episodes?extended=full'
                        )
                        for i in traktInfo:
                            if imdb == i['movie']['ids']['imdb']:
                                # Calculating Offset to seconds
                                offset = (float(i['progress'] / 100) *
                                          int(i['movie']['runtime']) * 60)

                    if control.setting('bookmarks.auto') == 'false':
                        try:
                            yes = control.dialog.contextmenu([
                                "Resume",
                                control.lang(32501).encode('utf-8'),
                            ])
                        except:
                            yes = control.yesnoDialog(
                                "Resume", '', '', str(name),
                                control.lang(32503).encode('utf-8'),
                                control.lang(32501).encode('utf-8'))
                        if yes: offset = '0'

                    return offset

                except:
                    return '0'
            else:
                try:
                    offset = '0'

                    if not control.setting('bookmarks') == 'true':
                        raise Exception()

                    idFile = hashlib.md5()
                    for i in name:
                        idFile.update(str(i))
                    for i in year:
                        idFile.update(str(i))
                    idFile = str(idFile.hexdigest())

                    dbcon = database.connect(control.bookmarksFile)
                    dbcur = dbcon.cursor()
                    dbcur.execute(
                        "SELECT * FROM bookmark WHERE idFile = '%s'" % idFile)
                    match = dbcur.fetchone()
                    self.offset = str(match[1])
                    dbcon.commit()
                    if self.offset == '0': raise Exception()

                    minutes, seconds = divmod(float(self.offset), 60)
                    hours, minutes = divmod(minutes, 60)
                    label = '%02d:%02d:%02d' % (hours, minutes, seconds)
                    label = (control.lang(32502) % label).encode('utf-8')

                    if control.setting('bookmarks.auto') == 'false':

                        try:
                            yes = control.dialog.contextmenu([
                                label,
                                control.lang(32501).encode('utf-8'),
                            ])
                        except:
                            yes = control.yesnoDialog(
                                label, '', '', str(name),
                                control.lang(32503).encode('utf-8'),
                                control.lang(32501).encode('utf-8'))
                        if yes: self.offset = '0'

                    return self.offset
                except:
                    return offset
        else:
            return offset
Esempio n. 24
0
    premiumize.library_play().play(name, id)

elif action == 'selectivelibrary_nav':
    from resources.lib.api import premiumize
    premiumize.selectivelibrary_nav()

elif action == 'selectiveLibraryManager':
    from resources.lib.api import premiumize
    premiumize.selectiveLibraryManager(id, name)

elif action == 'premiumizeLibrary':
    import shutil, os, time, xbmc
    from resources.lib.modules import control
    from resources.lib.api import premiumize
    yes = control.yesnoDialog(
        'This will Create Strm Files based on your Cloud Folder',
        'Are you sure you want to continue?', '')
    #print ("PREMIUMIZE SELECTION", yes)
    if yes == 1:
        try:
            libraryPath = xbmc.translatePath(control.setting('library.path'))
            if control.setting('library.deleteold') != 'true':
                raise Exception()
            try:
                shutil.rmtree(libraryPath)
            except:
                pass
            for root, dirs, files in os.walk(libraryPath, topdown=True):
                dirs[:] = [d for d in dirs]
                for name in files:
                    try:
Esempio n. 25
0
def authTrakt():
    from resources.lib.modules import client
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog("Konto bereits vorhanden",
                                   "Möchten Sie das Konto zurücksetzen?", '',
                                   'Trakt'):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        result = getTraktAsJson('/oauth/device/code',
                                {'client_id': V2_API_KEY})
        verification_url = ("Besuche: [COLOR skyblue]%s[/COLOR]" %
                            result['verification_url'])
        user_code = (
            "Wenn angewiesen, bitte eingeben: [COLOR skyblue]%s[/COLOR]" %
            result['user_code'])
        expires_in = int(result['expires_in'])
        device_code = result['device_code']
        interval = result['interval']

        progressDialog = control.progressDialog
        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
                    })
                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 = client.request(urlparse.urljoin(BASE_URL, '/users/me'),
                                headers=headers)
        result = utils.json_loads_as_str(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.user2',
                           value=user)  #Notwendig für korrekte settings.xml
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        pass
Esempio n. 26
0
def addDownload(name, url, image, provider=None):
    try:

        def download():
            return []

        result = cache.Nightmare_download_get(download,
                                              600000000,
                                              table='rel_dl')
        result = [i['name'] for i in result]
    except:
        pass

    try:
        if name in result:
            return control.infoDialog('Item Already In Your Queue', name)
    except:
        pass

    from resources.lib.indexers import movies, tvshows, episodes

    try:
        u = url.split('|')[0]
        try:
            headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1]))
        except:
            headers = dict('')

        ext = os.path.splitext(urlparse.urlparse(u).path)[1][1:].lower()
        if ext == 'm3u8': raise Exception()
        if not ext in ['mp4', 'm4a', 'mp3', 'aac', 'mkv', 'flv', 'avi', 'mpg']:
            ext = 'mp4'
        dest = name + '.' + ext

        req = urllib2.Request(u, headers=headers)
        resp = urllib2.urlopen(req, timeout=30)
        size = int(resp.headers['Content-Length'])
        size = ' %.2f GB' % (float(size) / 1073741824)

        no = control.yesnoDialog(dest, 'Complete file is' + size,
                                 'Continue with download?',
                                 name + ' - ' + 'Confirm Download', 'Confirm',
                                 'Cancel')

        if no: return
    except:
        return control.infoDialog('Unable to download')
        pass

    def download():
        return [{'name': name, 'url': url, 'image': image}]

    result = cache.Nightmare_download_get(download, 600000000, table='rel_dl')
    result = [i for i in result if not i['url'] == url]

    def download():
        return result + [{'name': name, 'url': url, 'image': image}]

    result = cache.Nightmare_download_get(download, 0, table='rel_dl')

    control.infoDialog('Item Added to Queue', name)
Esempio n. 27
0
    from resources.lib.sources import sources
    sources().alterSources(url, meta)

elif action == 'clearSources':
    from resources.lib.sources import sources
    sources().clearSources()
	
elif action == 'clearProgress':
    from resources.lib.modules import control
    import os,xbmc,xbmcaddon,xbmcgui
    dialog = xbmcgui.Dialog()
    addonInfo = xbmcaddon.Addon().getAddonInfo
    dataPath = xbmc.translatePath(addonInfo('profile')).decode('utf-8')
    favouritesFile = os.path.join(dataPath, 'favourites.db')
    progressFile = os.path.join(dataPath, 'progress.db')
    yes = control.yesnoDialog(control.lang(32056).encode('utf-8'), '', '')
    if yes:
		try: 
			os.remove(progressFile)
			dialog.ok('Clear Progress','Clear Progress Complete','','')
		except:
			dialog.ok('Clear Progress','There was an error Deleting the Database','','')		
		
	
elif action == 'urlresolversettings':
    import urlresolver
    urlresolver.display_settings()	
	
elif action == 'movieToLibrary':
    from resources.lib.sources import sources
    sources().movieToLibrary(title,year,imdb,meta)
Esempio n. 28
0
def doDownload(url, dest, title, image, headers):
	file = dest.rsplit(os.sep, 1)[-1]
	resp = getResponse(url, headers, 0)
	if not resp:
		control.hide()
		control.okDialog(title, dest + 'Download failed: No response from server')
		return
	try: content = int(resp.headers['Content-Length'])
	except: content = 0

	try: resumable = 'bytes' in resp.headers['Accept-Ranges'].lower()
	except: resumable = False

	if content < 1:
		control.hide()
		control.okDialog(title, file + 'Unknown filesize: Unable to download')
		return
	size = 1024 * 1024
	# mb = content / (1024 * 1024)
	gb = str(round(content / float(1073741824), 2))

	if content < size:
		size = content
	total = 0
	notify = 0
	errors = 0
	count = 0
	resume = 0
	sleep = 0
	control.hide()
	if control.yesnoDialog('Name to save: %s' % file, 'File Size: %sGB' % gb, 'Continue with download?', 'Confirm Download', 'Confirm',  'Cancel') == 1:
		return

	#f = open(dest, mode='wb')
	f = control.openFile(dest, 'w')
	chunk  = None
	chunks = []

	while True:
		downloaded = total
		for c in chunks:
			downloaded += len(c)
		percent = min(100 * downloaded / content, 100)
		if percent >= notify:
			control.notification(title=title + ' - Download Progress - ' + str(percent)+'%', message=dest, icon=image, time=10000)
			notify += 10
		chunk = None
		error = False
		try:
			chunk  = resp.read(size)
			if not chunk:
				if percent < 99:
					error = True
				else:
					while len(chunks) > 0:
						c = chunks.pop(0)
						f.write(c)
						del c
					f.close()
					return done(title, dest, True)
		except Exception as e:
			log_utils.log('DOWNNLOADER EXCEPTION | %s' % str(e), __name__, log_utils.LOGDEBUG)
			error = True
			sleep = 10
			errno = 0
			if hasattr(e, 'errno'):
				errno = e.errno
			if errno == 10035: # 'A non-blocking socket operation could not be completed immediately'
				pass
			if errno == 10054: #'An existing connection was forcibly closed by the remote host'
				errors = 10 #force resume
				sleep  = 30
			if errno == 11001: # 'getaddrinfo failed'
				errors = 10 #force resume
				sleep  = 30

		if chunk:
			errors = 0
			chunks.append(chunk)
			if len(chunks) > 5:
				c = chunks.pop(0)
				f.write(c)
				total += len(c)
				del c

		if error:
			errors += 1
			count  += 1
			control.sleep(sleep*1000)

		if (resumable and errors > 0) or errors >= 10:
			if (not resumable and resume >= 50) or resume >= 500:
				#Give up!
				return done(title, dest, False)
			resume += 1
			errors  = 0
			if resumable:
				chunks  = []
				#create new response
				resp = getResponse(url, headers, total)
			else: pass
Esempio n. 29
0
 def dialog(url):
     self.disableScraper = control.yesnoDialog(
         'To watch this video visit from any device',
         '[COLOR skyblue]%s[/COLOR]' % url, '', 'Torba',
         'Cancel', 'Settings')
Esempio n. 30
0
elif action == 'backup_restore':
    from resources.lib.modules import wiz
    typeOfBackup = ['BACKUP', 'RESTORE']
    s_type = control.selectDialog(typeOfBackup)
    if s_type == 0:
        modes = ['Full Backup', 'UserData Backup']
        select = control.selectDialog(modes)
        if select == 0: wiz.backup(mode='full')
        elif select == 1: wiz.backup(mode='userdata')
    elif s_type == 1: wiz.restoreFolder()

elif action == 'reloadMySkin':
    from resources.lib.modules import toolz
    yesDialog = control.yesnoDialog(AddonTitle,
                                    'Are you sure you want to Reload Skin?',
                                    yeslabel='Yes',
                                    nolabel='No')
    if yesDialog:
        toolz.ReloadMySkin()

elif action == 'reloadProfile':
    from resources.lib.modules import toolz
    yesDialog = control.yesnoDialog(AddonTitle,
                                    'Are you sure you want to Reload Profile?',
                                    yeslabel='Yes',
                                    nolabel='No')
    if yesDialog:
        toolz.reloadProfile(tools.getInfo('System.ProfileName'))

elif action == 'fresh_start':
    yesDialog = control.yesnoDialog(
Esempio n. 31
0
	def range(self, url, list_name):
		control.hide()
		if not control.yesnoDialog(control.lang(32555), '', ''): return
		try:
			if 'traktcollection' in url: message = 32661
			elif 'traktwatchlist' in url: message = 32662
			elif all(i in url for i in ['trakt', '/me/', '/lists/']): message = 32663
			elif all(i in url for i in ['trakt', '/lists/']) and '/me/' not in url: message = 32664
			elif 'tmdb_watchlist' in url: message = 32679
			elif 'tmdb_favorites' in url: message = 32680
			elif all(i in url for i in ['themoviedb', '/list/']): message = 32681
			else: message = 'list import'
		except:
			log_utils.error()

		if general_notification:
			if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'):
				control.notification(message=message)

		items = []
		try:
			if 'trakt' in url:
				if 'traktcollection' in url: url = 'https://api.trakt.tv/users/me/collection/shows'
				if 'traktwatchlist' in url: url = 'https://api.trakt.tv/users/me/watchlist/shows'
				from resources.lib.menus import tvshows
				items = tvshows.TVshows().trakt_list(url, control.setting('trakt.user').strip())

			if 'tmdb' in url:
				if 'tmdb_watchlist' in url:
					url = 'https://api.themoviedb.org/3/account/{account_id}/watchlist/tv?api_key=%s&session_id=%s' % ('%s', tmdb_session_id)
				if 'tmdb_favorites' in url: 
					url = 'https://api.themoviedb.org/3/account/{account_id}/favorite/tv?api_key=%s&session_id=%s' % ('%s', tmdb_session_id) 
				from resources.lib.indexers import tmdb
				items = tmdb.TVshows().tmdb_list(url)

			if (all(i in url for i in ['themoviedb', '/list/'])):
				url = url.split('&sort_by')[0]
				from resources.lib.indexers import tmdb
				items = tmdb.TVshows().tmdb_collections_list(url)
		except:
			log_utils.error()

		if items is None or items == []:
			if general_notification: control.notification(title=message, message=33049)
			return

		contains = lib_tools().ckKodiSources()

		total_added = 0
		for i in items:
			if control.monitor.abortRequested(): return sys.exit()
			try:
				files_added = self.add(i['title'], i['year'], i['imdb'], i['tmdb'], i['tvdb'], range=True)
				if general_notification and files_added > 0: control.notification(title=i['title'], message=32554)
				if files_added > 0: total_added += 1
			except:
				log_utils.error()

		try:
			type = 'tvshows'
			control.makeFile(control.dataPath)
			dbcon = database.connect(control.libcacheFile)
			dbcur = dbcon.cursor()
			dbcur.execute('''CREATE TABLE IF NOT EXISTS lists (type TEXT, list_name TEXT, url TEXT, UNIQUE(type, list_name, url));''')
			dbcur.execute('''INSERT OR REPLACE INTO lists Values (?, ?, ?)''', (type, list_name, url))
			dbcur.connection.commit()
		except:
			log_utils.error()
		finally:
			dbcur.close() ; dbcon.close()

		if self.library_update == 'true' and not control.condVisibility('Library.IsScanningVideo') and total_added > 0:
			if contains:
				control.sleep(10000)
				control.execute('UpdateLibrary(video)')
			elif general_notification:
				control.notification(message=32103)
Esempio n. 32
0
 def dialog(url):
     try: self.disableScraper = control.yesnoDialog('To watch this video visit from any device', '[COLOR skyblue]%s[/COLOR]' % url, '', 'Torba', 'Cancel', 'Settings')
     except: pass
Esempio n. 33
0
    wind = bv.Viewer('My first window')
    wind.doModal()
    del wind

###########################################################################################
elif mode[0]=='my_lists':
    lists = myLists.getLists()
    for ls in lists:
        delete = addon.build_plugin_url({'mode':'remove_list','name':ls[0]})
        context = [('Remove list','RunPlugin(%s)'%delete)]
        addon.add_item({'mode': 'open_list', 'path':ls[1], 'name':ls[0]}, {'title': ls[0]}, img=icon_path('my_lists.jpg'), fanart=fanart, is_folder=True, contextmenu_items=context)
    addon.add_item({'mode':'add_list'},{'title':'[B][COLOR green]Add list...[/COLOR][/B]'},img=icon_path('my_lists.jpg'), fanart=fanart, is_folder=True)
    addon.end_of_directory()

elif mode[0]=='add_list':
    answ = control.yesnoDialog('Do you want to add local list or remote list?','', '' ,yeslabel='Remote',nolabel='Local')
    
    #remote
    if str(answ)=='1':
        path = control.get_keyboard('Enter list URL:')

        name = control.get_keyboard('Enter list title:')
        if path and name:
            good = client.request(path)
            if good:
                myLists.addList(name,path)
            else:
                control.infoDialog('Cannot connect to list.',heading='Castaway Lists')
        else:
            control.infoDialog('A problem occured. Try again!',heading='Castaway Lists')
Esempio n. 34
0
    def get(self,
            name,
            imdb=None,
            tmdb=None,
            tvdb=None,
            season=None,
            episode=None,
            year='0',
            runtime=None,
            ck=False):
        offset = '0'
        if not runtime or runtime == 'None':
            return offset  # TMDB sometimes return None as string
        scrobbble = 'Local Bookmark'
        if control.setting('bookmarks') != 'true': return offset
        if control.setting('trakt.scrobble') == 'true' and control.setting(
                'resume.source') == '1':
            try:
                scrobbble = 'Trakt Scrobble'
                from resources.lib.modules import traktsync
                progress = float(
                    traktsync.fetch_bookmarks(imdb, tmdb, tvdb, season,
                                              episode))
                offset = (float(progress / 100) * int(runtime))
                seekable = (2 <= progress <= 85)
                if not seekable: return '0'
            except:
                log_utils.error()
                return '0'
        else:
            try:
                dbcon = database.connect(control.bookmarksFile)
                dbcur = dbcon.cursor()
                dbcur.execute(
                    '''CREATE TABLE IF NOT EXISTS bookmark (idFile TEXT, timeInSeconds TEXT, Name TEXT, year TEXT, UNIQUE(idFile));'''
                )
                if not year or year == 'None': return offset
                years = [str(year), str(int(year) + 1), str(int(year) - 1)]
                #helps fix random cases where trakt and imdb, or tvdb, differ by a year for eps
                match = dbcur.execute(
                    '''SELECT * FROM bookmark WHERE Name="%s" AND year IN (%s)'''
                    % (name, ','.join(i for i in years))).fetchone()
            except:
                log_utils.error()
                return offset
            finally:
                dbcur.close()
                dbcon.close()

            if not match: return offset
            offset = str(match[1])

        if ck: return offset
        minutes, seconds = divmod(float(offset), 60)
        hours, minutes = divmod(minutes, 60)
        label = '%02d:%02d:%02d' % (hours, minutes, seconds)
        label = control.lang(32502) % label
        if control.setting('bookmarks.auto') == 'false':
            if control.yesnoDialog(label, scrobbble, '', str(name),
                                   control.lang(32503), control.lang(32501)):
                offset = '0'
        return offset
Esempio n. 35
0
            fanart=fanart,
            is_folder=True,
            contextmenu_items=context,
        )
    addon.add_item(
        {"mode": "add_list"},
        {"title": "[B][COLOR green]Add list...[/COLOR][/B]"},
        img=icon_path("my_lists.jpg"),
        fanart=fanart,
        is_folder=True,
    )
    addon.end_of_directory()

elif mode[0] == "add_list":
    answ = control.yesnoDialog(
        "Do you want to add local list or remote list?", "", "", yeslabel="Remote", nolabel="Local"
    )

    # remote
    if str(answ) == "1":
        path = control.get_keyboard("Enter list URL:")

        name = control.get_keyboard("Enter list title:")
        if path and name:
            good = client.request(path)
            if good:
                myLists.addList(name, path)
            else:
                control.infoDialog("Cannot connect to list.", heading="Castaway Lists")
        else:
            control.infoDialog("A problem occured. Try again!", heading="Castaway Lists")
Esempio n. 36
0
def authTrakt():
    try:
        if getTraktCredentialsInfo():
            if control.yesnoDialog(control.lang(32511), control.lang(32512),
                                   '', 'Trakt'):
                control.setSetting(id='trakt.isauthed', value='')
                control.setSetting(id='trakt.username', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        result = getTraktAsJson('/oauth/device/code',
                                {'client_id': V2_API_KEY})
        verification_url = (control.lang(32513) %
                            result['verification_url']).encode('utf-8')
        user_code = (control.lang(32514) % result['user_code']).encode('utf-8')
        expires_in = int(result['expires_in'])
        device_code = result['device_code']
        interval = result['interval']
        progressDialog = control.progressDialog
        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: continue
                r = getTraktAsJson(
                    '/oauth/device/token', {
                        'client_id': V2_API_KEY,
                        'client_secret': CLIENT_SECRET,
                        'code': device_code
                    })
                if not r: continue
                if 'access_token' in r: break
            except:
                log_utils.error()
        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 = client.request(urljoin(BASE_URL, '/users/me'),
                                headers=headers)
        result = utils.json_loads_as_str(result)

        username = result['username']

        control.setSetting(id='trakt.isauthed', value='true')
        control.setSetting(id='trakt.username', value=username)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        log_utils.error()
Esempio n. 37
0
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog(
                    control.lang(30479).encode('utf-8'),
                    control.lang(30481).encode('utf-8'), '', 'Trakt',
                    control.lang(30483).encode('utf-8'),
                    control.lang(30482).encode('utf-8')):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        result = getTrakt(
            '/oauth/device/code', {
                'client_id':
                'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa'
            })
        result = json.loads(result)
        verification_url = (control.lang(30416) + '[COLOR skyblue]%s[/COLOR]' %
                            result['verification_url']).encode('utf-8')
        user_code = (
            control.lang(30417) +
            '[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 = control.progressDialog
        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 = getTrakt(
                    '/oauth/device/token', {
                        'client_id':
                        'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa',
                        'client_secret':
                        '90a1840447a1e39d350023263902fe7010338d19789e6260f18df56a8b07a68a',
                        'code': device_code
                    })
                r = json.loads(r)
                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':
            'c029c80fd3d3a5284ee820ba1cf7f0221da8976b8ee5e6c4af714c22fc4f46fa',
            'trakt-api-version': '2',
            'Authorization': 'Bearer %s' % token
        }

        result = client.request('http://api-v2launch.trakt.tv/users/me',
                                headers=headers)
        result = json.loads(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('3.1')
    def add_uncached_torrent(self, magnet_url, pack=False):
        def _return_failed(message=control.lang(33586)):
            try:
                control.progressDialog.close()
            except:
                pass
            self.delete_torrent(torrent_id)
            control.hide()
            control.sleep(500)
            control.okDialog(title=control.lang(40018), message=message)
            return False

        control.busy()
        try:
            active_count = self.torrents_activeCount()
            if active_count['nb'] >= active_count['limit']:
                return _return_failed()
        except:
            pass
        interval = 5
        stalled = ['magnet_error', 'error', 'virus', 'dead']
        extensions = supported_video_extensions()
        torrent_id = self.add_magnet(magnet_url)
        if not torrent_id:
            return _return_failed()
        torrent_info = self.torrent_info(torrent_id)
        if 'error_code' in torrent_info:
            return _return_failed()
        status = torrent_info['status']
        if any(x in status for x in stalled):
            return _return_failed(status)
        if status == 'magnet_conversion':
            line1 = control.lang(40013)
            line2 = torrent_info['filename']
            line3 = control.lang(40012) % str(torrent_info['seeders'])
            timeout = 100
            control.progressDialog.create(control.lang(40018), line1, line2,
                                          line3)
            while status == 'magnet_conversion' and timeout > 0:
                control.progressDialog.update(timeout, line3=line3)
                if control.monitor.abortRequested():
                    return sys.exit()
                try:
                    if control.progressDialog.iscanceled():
                        return _return_failed(control.lang(40014))
                except:
                    pass
                timeout -= interval
                control.sleep(1000 * interval)
                torrent_info = self.torrent_info(torrent_id)
                status = torrent_info['status']
                if any(x in status for x in stalled):
                    return _return_failed()
                line3 = control.lang(40012) % str(torrent_info['seeders'])
            try:
                control.progressDialog.close()
            except:
                pass
        if status == 'magnet_conversion':
            return _return_failed()
        if status == 'waiting_files_selection':
            video_files = []
            all_files = torrent_info['files']
            for item in all_files:
                if any(item['path'].lower().endswith(x) for x in extensions):
                    video_files.append(item)
            if pack:
                try:
                    if len(video_files) == 0: return _return_failed()
                    video_files = sorted(video_files, key=lambda x: x['path'])
                    torrent_keys = [str(i['id']) for i in video_files]
                    if not torrent_keys:
                        return _return_failed(control.lang(40014))
                    torrent_keys = ','.join(torrent_keys)
                    self.add_torrent_select(torrent_id, torrent_keys)
                    control.okDialog(title='default',
                                     message=control.lang(40017) %
                                     control.lang(40058))
                    control.hide()
                    return True
                except:
                    return _return_failed()
            else:
                try:
                    video = max(video_files, key=lambda x: x['bytes'])
                    file_id = video['id']
                except ValueError:
                    return _return_failed()
                self.add_torrent_select(torrent_id, str(file_id))
            control.sleep(2000)
            torrent_info = self.torrent_info(torrent_id)
            status = torrent_info['status']
            if status == 'downloaded':
                control.hide()
                control.notification(message=control.lang(32057))
                return True
            file_size = round(float(video['bytes']) / (1000**3), 2)
            line1 = '%s...' % (control.lang(40017) % control.lang(40058))
            line2 = torrent_info['filename']
            line3 = status
            control.progressDialog.create(control.lang(40018), line1, line2,
                                          line3)
            while not status == 'downloaded':
                control.sleep(1000 * interval)
                torrent_info = self.torrent_info(torrent_id)
                status = torrent_info['status']
                if status == 'downloading':
                    line3 = control.lang(40011) % (
                        file_size,
                        round(float(torrent_info['speed']) / (1000**2), 2),
                        torrent_info['seeders'], torrent_info['progress'])
                else:
                    line3 = status
                control.progressDialog.update(int(
                    float(torrent_info['progress'])),
                                              line3=line3)
                if control.monitor.abortRequested(): return sys.exit()
                try:
                    if control.progressDialog.iscanceled():
                        if control.yesnoDialog(
                                'Delete RD download also?',
                                'No will continue the download',
                                'but close dialog'):
                            return _return_failed(control.lang(40014))
                        else:
                            control.progressDialog.close()
                            control.hide()
                            return False
                except:
                    pass
                if any(x in status for x in stalled):
                    return _return_failed()
            try:
                control.progressDialog.close()
            except:
                pass
            control.hide()
            return True
        control.hide()
        return False
Esempio n. 39
0
    def resumePlayback(self):
        while True:
            try:  # KODI 18 LEIA CHANGES TO PLAYER NOW REQUIRES isPlayingVideo to make sure Video is Playing
                if not self.isPlayingVideo(): continue
                try:
                    timeTotal = self.getTotalTime()
                except:
                    timeTotal = 0
                if timeTotal != None and timeTotal != 0: break
                time.sleep(0.5)
            except:
                continue

        progress = '0'

        if self.autoResume == 'true': dialog = False
        else: dialog = True

        # NEED TO CALL TRAKTPLAYBACK OUTSIDE BOOKMARKS TO GET TOTALTIME AND OTHER SELF VARIABLES
        if control.setting('trakt.scrobblePlayback') == 'true':
            try:
                self.seekStatus = True
                progress = self.traktGetPlayback()

                if progress > 0:
                    if timeTotal > 0:
                        seconds = (progress * timeTotal) / 100.0
                        if seconds > 0:
                            try:
                                if dialog == False: raise Exception()
                                timeMinutes, timeSeconds = divmod(
                                    float(seconds), 60)
                                timeHours, timeMinutes = divmod(
                                    timeMinutes, 60)
                                label = '%02d:%02d:%02d' % (
                                    timeHours, timeMinutes, timeSeconds)
                                label = (label).encode('utf-8')
                                label = "[T] Resume: " + label
                                try:
                                    yes = control.dialog.contextmenu([
                                        label,
                                        control.lang(32501).encode('utf-8'),
                                    ])
                                except:
                                    yes = control.yesnoDialog(
                                        label, '', '', str(name),
                                        control.lang(32503).encode('utf-8'),
                                        control.lang(32501).encode('utf-8'))
                                if yes: seconds = 0
                            except:
                                pass

                        if seconds > 0: self.seekTime(seconds)
            except:
                progress = 0

# FALLBACK TO DATABASE AND REMOTEDB BOOKMARKS
        if progress == None or progress == '' or progress == 0:
            self.seekStatus = True
            self.offset = bookmarks().get(self.bookMarkName, dialog=dialog)
            if self.offset != '0' and self.offset != None:
                self.seekTime(float(self.offset))

        self.totalTime = self.getTotalTime()
        self.currentTime = self.getTime()
        self.traktSetPlayback('start')
Esempio n. 40
0
def rdAuthorize():
    try:
        CLIENT_ID = 'X245A4XAIBGVM'
        USER_AGENT = 'Kodi Exodus/3.0'

        if not '' in credentials()['realdebrid'].values():
            if control.yesnoDialog(
                    control.lang(30411).encode('utf-8'),
                    control.lang(30413).encode('utf-8'), '', 'RealDebrid',
                    control.lang(30415).encode('utf-8'),
                    control.lang(30414).encode('utf-8')):
                control.setSetting(id='realdebrid.id', value='')
                control.setSetting(id='realdebrid.secret', value='')
                control.setSetting(id='realdebrid.token', value='')
                control.setSetting(id='realdebrid.refresh', value='')
                control.setSetting(id='realdebrid.auth', value='')
            raise Exception()

        headers = {'User-Agent': USER_AGENT}
        url = 'https://api.real-debrid.com/oauth/v2/device/code?client_id=%s&new_credentials=yes' % (
            CLIENT_ID)
        result = client.request(url, headers=headers)
        result = json.loads(result)
        verification_url = control.lang(30416).encode(
            'utf-8') + '[COLOR skyblue]%s[/COLOR]' % (
                result['verification_url'])
        user_code = control.lang(30417).encode(
            'utf-8') + '[COLOR skyblue]%s[/COLOR]' % (result['user_code'])
        device_code = result['device_code']
        interval = result['interval']

        progressDialog = control.progressDialog
        progressDialog.create('RealDebrid', verification_url, user_code)

        for i in range(0, 3600):
            try:
                if progressDialog.iscanceled(): break
                time.sleep(1)
                if not float(i) % interval == 0: raise Exception()
                url = 'https://api.real-debrid.com/oauth/v2/device/credentials?client_id=%s&code=%s' % (
                    CLIENT_ID, device_code)
                result = client.request(url, headers=headers, error=True)
                result = json.loads(result)
                if 'client_secret' in result: break
            except:
                pass

        try:
            progressDialog.close()
        except:
            pass

        id, secret = result['client_id'], result['client_secret']

        url = 'https://api.real-debrid.com/oauth/v2/token'
        post = urllib.urlencode({
            'client_id':
            id,
            'client_secret':
            secret,
            'code':
            device_code,
            'grant_type':
            'http://oauth.net/grant_type/device/1.0'
        })

        result = client.request(url, post=post, headers=headers)
        result = json.loads(result)

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

        control.setSetting(id='realdebrid.id', value=id)
        control.setSetting(id='realdebrid.secret', value=secret)
        control.setSetting(id='realdebrid.token', value=token)
        control.setSetting(id='realdebrid.refresh', value=refresh)
        control.setSetting(id='realdebrid.auth', value='*************')
        raise Exception()
    except:
        control.openSettings('3.13')
Esempio n. 41
0
    def add_uncached_torrent(self, magnet_url, pack=False):
        def _transfer_info(transfer_id):
            info = self.list_transfer()
            if 'status' in info and info['status'] == 'success':
                for item in info['transfers']:
                    if item['id'] == transfer_id:
                        return item
            return {}

        def _return_failed(message=control.lang(33586)):
            try:
                control.progressDialog.close()
            except:
                pass
            self.delete_transfer(transfer_id)
            control.hide()
            control.sleep(500)
            control.okDialog(title=control.lang(40018), message=message)
            return False

        control.busy()
        extensions = supported_video_extensions()
        transfer_id = self.create_transfer(magnet_url)
        if not transfer_id:
            control.hide()
            return
        if not transfer_id['status'] == 'success':
            return _return_failed()
        transfer_id = transfer_id['id']
        transfer_info = _transfer_info(transfer_id)
        if not transfer_info:
            return _return_failed()
        if pack:
            control.hide()
            control.okDialog(title='default',
                             message=control.lang(40017) % control.lang(40057))
            return True
        interval = 5
        line1 = '%s...' % (control.lang(40017) % control.lang(40057))
        line2 = transfer_info['name']
        line3 = transfer_info['message']
        control.progressDialog.create(control.lang(40018), line1, line2, line3)
        while not transfer_info['status'] == 'seeding':
            control.sleep(1000 * interval)
            transfer_info = _transfer_info(transfer_id)
            line3 = transfer_info['message']
            control.progressDialog.update(int(
                float(transfer_info['progress']) * 100),
                                          line3=line3)
            if control.monitor.abortRequested():
                return sys.exit()
            try:
                if control.progressDialog.iscanceled():
                    if control.yesnoDialog('Delete PM download also?',
                                           'No will continue the download',
                                           'but close dialog'):
                        return _return_failed(control.lang(40014))
                    else:
                        control.progressDialog.close()
                        control.hide()
                        return False
            except:
                pass
            if transfer_info.get('status') == 'stalled':
                return _return_failed()
        control.sleep(1000 * interval)
        try:
            control.progressDialog.close()
        except:
            log_utils.error()
        control.hide()
        return True
Esempio n. 42
0
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog(control.lang(32511) + '[CR]' +
                                   control.lang(32512),
                                   heading='Trakt'):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.authed', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()

        result = getTraktAsJson('/oauth/device/code',
                                {'client_id': V2_API_KEY})
        verification_url = control.lang(32513) % result['verification_url']
        user_code = six.ensure_text(control.lang(32514) % result['user_code'])
        expires_in = int(result['expires_in'])
        device_code = result['device_code']
        interval = result['interval']

        progressDialog = control.progressDialog
        progressDialog.create('Trakt')

        for i in list(range(0, expires_in)):
            try:
                percent = int(100 * float(i) / int(expires_in))
                progressDialog.update(max(1, percent),
                                      verification_url + '[CR]' + user_code)
                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
                    })
                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 = client.request(urllib_parse.urljoin(BASE_URL, '/users/me'),
                                headers=headers)
        result = utils.json_loads_as_str(result)

        user = result['username']
        authed = '' if user == '' else str('yes')

        print('info - ' + token)
        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.authed', value=authed)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('4.0')
Esempio n. 43
0
 def emptyLog(self):
     #control.idle()
     yes = control.yesnoDialog(control.lang(32056))
     if not yes: return
     from resources.lib.modules import log_utils
     log_utils.empty_log()
Esempio n. 44
0
    def delete(self, type, folder_id=None, folder_name=None):
        try:
            if type == 'folder': url = folder_delete_url
            else: url = item_delete_url
            if not control.yesnoDialog(
                    control.lang(40050) % folder_name, '', ''):
                return
            data = {'id': folder_id}
            response = self._post(url, data=data)
            if not response: return
            if 'status' in response:
                if response.get('status') == 'success':
                    control.refresh()
        except:
            log_utils.error()


# # from resolveURL
# def get_all_hosters(self):
# try:
# response = self._get(list_services_path_url)
# if not response:
# return None
# aliases = response.get('aliases', {})
# patterns = response.get('regexpatterns', {})

# tldlist = []
# for tlds in aliases.values():
# for tld in tlds:
# tldlist.append(tld)
# if self.get_setting('torrents') == 'true':
# tldlist.extend([u'torrent', u'magnet'])
# regex_list = []
# for regexes in patterns.values():
# for regex in regexes:
# try:
# regex_list.append(re.compile(regex))
# except:
# log_utils.log('Throwing out bad Premiumize regex: %s' % regex, __name__, log_utils.LOGDEBUG)
# log_utils.log('Premiumize.me patterns: %s regex: (%d) hosts: %s' % (patterns, len(regex_list), tldlist), __name__, log_utils.LOGDEBUG)
# return tldlist, regex_list
# except Exception as e:
# log_utils.log('Error getting Premiumize hosts: %s' % e, __name__, log_utils.LOGDEBUG)
# return [], []

# # from resolveURL
# def valid_url(self, url, host):
# if url and self.get_setting('torrents') == 'true':
# url_lc = url.lower()
# if url_lc.endswith('.torrent') or url_lc.startswith('magnet:'):
# return True
# if not self.patterns or not self.hosts:
# self.hosts, self.patterns = self.get_all_hosters()
# if url:
# if not url.endswith('/'):
# url += '/'
# for pattern in self.patterns:
# if pattern.findall(url):
# return True
# elif host:
# if host.startswith('www.'):
# host = host.replace('www.', '')
# if any(host in item for item in self.hosts):
# return True
# return False
Esempio n. 45
0
def authTrakt():
    try:

        check = checkCredentials()
        if check == 'true':
            yes = control.yesnoDialog(
                control.lang(32511).encode('utf-8'),
                control.lang(32512).encode('utf-8'), '', 'Trakt')
            if yes:
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
                control.infoDialog('Trakt Account Reset: DONE',
                                   sound=True,
                                   icon='INFO')
            raise Exception()

        result = getTraktAsJson('/oauth/device/code', {'client_id': CLIENT_ID})
        verification_url = (control.lang(32513) %
                            result['verification_url']).encode('utf-8')
        user_code = (control.lang(32514) % result['user_code']).encode('utf-8')
        expires_in = int(result['expires_in'])
        device_code = result['device_code']
        interval = result['interval']

        # print ("TRAKT DEVICE CODE", device_code)
        # print ("TRAKT interval CODE", interval)
        # print ("TRAKT expires_in CODE", expires_in)
        progressDialog = control.progressDialog
        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': CLIENT_ID,
                        'client_secret': CLIENT_SECRET,
                        'code': device_code
                    })
                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': CLIENT_ID,
            'trakt-api-version': '2',
            'Authorization': 'Bearer %s' % token
        }

        result = requests.get(urlparse.urljoin(BASE_URL, '/users/me'),
                              headers=headers).content
        result = utils.json_loads_as_str(result)

        user = result['username']
        control.infoDialog('Trakt Account Verified', sound=True, icon='INFO')
        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        control.setSetting(id='indicators.alt', value='1')

        raise Exception()
    except:
        control.openSettings('3.1')
Esempio n. 46
0
    control.openSettings(id='script.mrknow.urlresolver')
elif action == 'queueItem':
    from resources.lib.modules import control
    from resources.lib.indexers.bob import Resolver, Indexer, replace_url

    item_urls = []
    selected_link = None
    play_now = False
    already_played = False
    if not url.endswith(".xml"):
        item_urls.append({'url': url, 'name': name, 'image': image})
    else:
        if control.yesnoDialog('Select the quality to queue',
                               '',
                               '',
                               yeslabel='HD',
                               nolabel='SD'):
            selected_link = "HD"
        else:
            selected_link = "SD"
        indexer = Indexer()
        indexer.bob_list(replace_url(url))
        indexer.worker()
        list = indexer.list
        try:
            for item in list:
                if item['name'] == 'All Episodes':
                    continue
                if control.setting("include_watched_queue") == "false":
                    if "playcount" in item and int(item["playcount"]) >= 1:
Esempio n. 47
0
def authTrakt():
    try:
        if getTraktCredentialsInfo() == True:
            if control.yesnoDialog("An account already exists.",
                                   "Do you want to reset?", '', 'Trakt'):
                control.setSetting(id='trakt.user', value='')
                control.setSetting(id='trakt.token', value='')
                control.setSetting(id='trakt.refresh', value='')
            raise Exception()
        result = getTraktAsJson('/oauth/device/code',
                                {'client_id': V2_API_KEY})
        verification_url = "1) Visit : [COLOR skyblue]" + result[
            'verification_url'] + "[/COLOR]"
        user_code = "2) When prompted enter : [COLOR skyblue]" + result[
            'user_code'] + "[/COLOR]"
        expires_in = int(result['expires_in'])
        device_code = result['device_code']
        interval = result['interval']
        progressDialog = control.progressDialog
        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
                    })
                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 = client.request(urlparse.urljoin(BASE_URL, '/users/me'),
                                headers=headers)
        result = utils.json_loads_as_str(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('3.1')
Esempio n. 48
0
def authTrakt():

    try:

        if getTraktCredentialsInfo() == True:

            if control.yesnoDialog(control.lang(32700).encode('utf-8'), control.lang(32701).encode('utf-8'), '', 'Trakt'):

                utils.setting('trakt.user', '');
                utils.setting('trakt.token', '');
                utils.setting('trakt.refresh', '');

            raise Exception();

        result = getTrakt('/oauth/device/code', {'client_id': '49e7f57ee0c22e6ca39649a9255f6097d10cbdb708a5f1c3dc196e615cce6549'});
        result = json.loads(result);

        verification_url = (control.lang(32702) % result['verification_url']).encode('utf-8');
        user_code = (control.lang(32703) % result['user_code']).encode('utf-8');
        expires_in = int(result['expires_in']);
        device_code = result['device_code'];
        interval = result['interval'];

        progressDialog = control.progressDialog;
        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 = getTrakt('/oauth/device/token', {'client_id': '49e7f57ee0c22e6ca39649a9255f6097d10cbdb708a5f1c3dc196e615cce6549', 'client_secret': '49288059527f042ac3e953419ecfd8c6783438ae966cd0b05982423e7fbb0259', 'code': device_code});
                r = json.loads(r);

                if 'access_token' in r: 
                    break;
            
            except:
                pass;

        try: 
            progressDialog.close();
        
        except: 
            pass;


        token = r['access_token'];
        refresh = r['refresh_token'];

        headers = {
            'Content-Type': 'application/json', 
            'trakt-api-key': '49e7f57ee0c22e6ca39649a9255f6097d10cbdb708a5f1c3dc196e615cce6549', 
            'trakt-api-version': '2', 
            'Authorization': 'Bearer %s' % token
        };

        result = client.request('http://api-v2launch.trakt.tv/users/me', headers=headers);
        result = json.loads(result);

        user = result['username'];

        utils.setting('trakt.user', user);
        utils.setting('trakt.token', token);
        utils.setting('trakt.refresh', refresh);

        raise Exception();

    except:
        control.openSettings('3.1');
Esempio n. 49
0
def doDownload(url, dest, title, image, headers):
	file = dest.rsplit(os.sep, 1)[-1]
	resp = getResponse(url, headers, 0)
	if not resp:
		control.hide()
		return control.okDialog(title, dest + 'Download failed: No response from server')
	try: content = int(resp.headers['Content-Length'])
	except: content = 0
	try: resumable = 'bytes' in resp.headers['Accept-Ranges'].lower()
	except: resumable = False
	if content < 1:
		control.hide()
		return control.okDialog(title, file + 'Unknown filesize: Unable to download')
	size = 1024 * 1024
	gb = str(round(content / float(1073741824), 2))
	if content < size:
		size = content
	total = 0
	notify = 0
	errors = 0
	count = 0
	resume = 0
	sleep = 0
	control.hide()
	if control.yesnoDialog('File Size: %sGB\nPath: %s\nContinue with download?' % (gb, dest), '', '', 'Confirm Download', 'Confirm',  'Cancel') == 1: return
	f = control.openFile(dest, 'w')
	chunk  = None
	chunks = []
	import xbmcgui
	while True:
		downloaded = total
		for c in chunks: downloaded += len(c)
		percent = min(100 * downloaded / content, 100)
		if percent >= notify:
			control.notification(title=title + ' - Download Progress - ' + str(int(percent)) + '%', message='', icon=image, time=3000) #xbmcgui.Dialog().notification() auto scroll time to complete supercedes allowed "time=" to run in Silvo, removed dest
			notify += 20
		chunk = None
		error = False
		try:
			chunk  = resp.read(size)
			if not chunk:
				if percent < 99: error = True
				else:
					while len(chunks) > 0:
						c = chunks.pop(0)
						f.write(c)
						del c
					f.close()
					log_utils.log('Download Complete: %s' % (dest), level=log_utils.LOGDEBUG)
					return done(title, dest, True)
		except:
			log_utils.error('DOWNNLOADER EXCEPTION: ')
			error = True
			sleep = 10
			errno = 0
			if hasattr(e, 'errno'):
				errno = e.errno
			if errno == 10035: # 'A non-blocking socket operation could not be completed immediately'
				pass
			if errno == 10054: #'An existing connection was forcibly closed by the remote host'
				errors = 10 #force resume
				sleep  = 30
			if errno == 11001: # 'getaddrinfo failed'
				errors = 10 #force resume
				sleep  = 30
		if chunk:
			errors = 0
			chunks.append(chunk)
			if len(chunks) > 5:
				c = chunks.pop(0)
				f.write(c)
				total += len(c)
				del c
		if error:
			errors += 1
			count  += 1
			control.sleep(sleep*1000)
		if (resumable and errors > 0) or errors >= 10:
			if (not resumable and resume >= 50) or resume >= 500: # Give up!
				log_utils.log('Download Canceled: %s - too many errors whilst downloading' % (dest), level=log_utils.LOGWARNING)
				return done(title, dest, False)
			resume += 1
			errors  = 0
			if resumable:
				chunks  = []
				resp = getResponse(url, headers, total) # create new response
			else: pass
Esempio n. 50
0
elif action == 'ResolverSettings':
    from resources.lib.modules import control

    control.openSettings(id='script.mrknow.urlresolver')
elif action == 'queueItem':
    from resources.lib.modules import control
    from resources.lib.indexers.bob import Resolver, Indexer, replace_url

    item_urls = []
    selected_link = None
    play_now = False
    already_played = False
    if not url.endswith(".xml"):
        item_urls.append({'url': url, 'name': name, 'image': image})
    else:
        if control.yesnoDialog('Select the quality to queue', '', '', yeslabel='HD', nolabel='SD'):
            selected_link = "HD"
        else:
            selected_link = "SD"
        indexer = Indexer()
        indexer.bob_list(replace_url(url))
        indexer.worker()
        list = indexer.list
        try:
            for item in list:
                if item['name'] == 'All Episodes':
                    continue
                if control.setting("include_watched_queue") == "false":
                    if "playcount" in item and int(item["playcount"]) >= 1:
                        continue
                if item['url'].endswith(".xml"):  # queueing tv show so need to get sublists
Esempio n. 51
0
    def add_uncached_torrent(self, magnet_url, pack=False):
        def _return_failed(message=control.lang(33586)):
            try:
                control.progressDialog.close()
            except:
                pass
            self.delete_transfer(transfer_id)
            control.hide()
            control.sleep(500)
            control.okDialog(title=control.lang(40018), message=message)
            return False

        control.busy()
        transfer_id = self.create_transfer(magnet_url)
        if not transfer_id:
            return _return_failed()
        transfer_info = self.list_transfer(transfer_id)
        if not transfer_info:
            return _return_failed()
        if pack:
            control.hide()
            control.okDialog(title='default',
                             message=control.lang(40017) % control.lang(40059))
            return True
        interval = 5
        line1 = '%s...' % (control.lang(40017) % control.lang(40059))
        line2 = transfer_info['filename']
        line3 = transfer_info['status']
        control.progressDialog.create(control.lang(40018), line1, line2, line3)
        while not transfer_info['statusCode'] == 4:
            control.sleep(1000 * interval)
            transfer_info = self.list_transfer(transfer_id)
            file_size = transfer_info['size']
            line2 = transfer_info['filename']
            if transfer_info['statusCode'] == 1:
                download_speed = round(
                    float(transfer_info['downloadSpeed']) / (1000**2), 2)
                progress = int(
                    float(transfer_info['downloaded']) / file_size *
                    100) if file_size > 0 else 0
                line3 = control.lang(40016) % (
                    download_speed, transfer_info['seeders'], progress,
                    round(float(file_size) / (1000**3), 2))
            elif transfer_info['statusCode'] == 3:
                upload_speed = round(
                    float(transfer_info['uploadSpeed']) / (1000**2), 2)
                progress = int(
                    float(transfer_info['uploaded']) / file_size *
                    100) if file_size > 0 else 0
                line3 = control.lang(40015) % (upload_speed, progress,
                                               round(
                                                   float(file_size) /
                                                   (1000**3), 2))
            else:
                line3 = transfer_info['status']
                progress = 0
            control.progressDialog.update(progress, line2=line2, line3=line3)
            if control.monitor.abortRequested():
                return sys.exit()
            try:
                if control.progressDialog.iscanceled():
                    if control.yesnoDialog('Delete AD download also?',
                                           'No will continue the download',
                                           'but close dialog'):
                        return _return_failed(control.lang(40014))
                    else:
                        control.progressDialog.close()
                        control.hide()
                        return False
            except:
                pass
            if 5 <= transfer_info['statusCode'] <= 10:
                return _return_failed()
        control.sleep(1000 * interval)
        try:
            control.progressDialog.close()
        except:
            pass
        control.hide()
        return True
    def onAction(self, action):
        try:
            if action in self.selection_actions:
                focus_id = self.getFocusId()
                if focus_id == 2060:  # listItems
                    position = self.get_position(self.window_id)
                    chosen_listitem = self.item_list[position]
                    imdb = chosen_listitem.getProperty('venom.imdb')
                    if chosen_listitem.getProperty(
                            'venom.isSelected') == 'true':
                        chosen_listitem.setProperty('venom.isSelected', '')
                        if imdb in str(self.selected_items):
                            pos = next(
                                (index
                                 for (index,
                                      d) in enumerate(self.selected_items)
                                 if d["imdb"] == imdb), None)
                            self.selected_items.pop(pos)
                    else:
                        chosen_listitem.setProperty('venom.isSelected', 'true')
                        imdb = chosen_listitem.getProperty('venom.imdb')
                        tvdb = chosen_listitem.getProperty('venom.tvdb')
                        season = chosen_listitem.getProperty('venom.season')
                        episode = chosen_listitem.getProperty('venom.episode')
                        self.selected_items.append({
                            'imdb': imdb,
                            'tvdb': tvdb,
                            'season': season,
                            'episode': episode
                        })
                elif focus_id == 2061:  # OK Button
                    self.close()
                elif focus_id == 2062:  # Cancel Button
                    self.selected_items = None
                    self.close()
                elif focus_id == 2063:  # Select All Button
                    for item in self.item_list:
                        item.setProperty('venom.isSelected', 'true')
                elif focus_id == 2045:  # Stop Trailer Playback Button
                    self.execute_code('PlayerControl(Stop)')
                    sleep(500)
                    self.setFocusId(self.window_id)

            elif action in self.context_actions:
                cm = []
                chosen_listitem = self.item_list[self.get_position(
                    self.window_id)]
                # media_type = chosen_listitem.getProperty('venom.media_type')
                source_trailer = chosen_listitem.getProperty('venom.trailer')
                if not source_trailer:
                    from resources.lib.modules import trailer
                    source_trailer = trailer.Trailer().worker(
                        'show',
                        chosen_listitem.getProperty('venom.tvshowtitle'),
                        chosen_listitem.getProperty('venom.year'), None,
                        chosen_listitem.getProperty('venom.imdb'))

                if source_trailer:
                    cm += [('[B]Play Trailer[/B]', 'playTrailer')]
                cm += [('[B]Browse Series[/B]', 'browseSeries')]
                chosen_cm_item = dialog.contextmenu([i[0] for i in cm])
                if chosen_cm_item == -1: return
                cm_action = cm[chosen_cm_item][1]

                if cm_action == 'playTrailer':
                    self.execute_code('PlayMedia(%s, 1)' % source_trailer)
                    total_sleep = 0
                    while True:
                        sleep(500)
                        total_sleep += 500
                        self.hasVideo = condVisibility('Player.HasVideo')
                        if self.hasVideo or total_sleep >= 10000: break
                    if self.hasVideo:
                        self.setFocusId(2045)
                        while (condVisibility('Player.HasVideo')
                               and not monitor.abortRequested()):
                            self.setProgressBar()
                            sleep(1000)
                        self.hasVideo = False
                        self.progressBarReset()
                        self.setFocusId(self.window_id)
                    else:
                        self.setFocusId(self.window_id)

                if cm_action == 'browseSeries':
                    systvshowtitle = quote_plus(
                        chosen_listitem.getProperty('venom.tvshowtitle'))
                    year = chosen_listitem.getProperty('venom.year')
                    imdb = chosen_listitem.getProperty('venom.imdb')
                    tmdb = chosen_listitem.getProperty('venom.tmdb')
                    tvdb = chosen_listitem.getProperty('venom.tvdb')
                    from resources.lib.modules.control import lang
                    if not yesnoDialog(lang(32182), '', ''): return
                    self.chosen_hide, self.chosen_unhide = None, None
                    self.close()
                    sysart = quote_plus(
                        chosen_listitem.getProperty('venom.art'))
                    self.execute_code(
                        'ActivateWindow(Videos,plugin://plugin.video.venom/?action=seasons&tvshowtitle=%s&year=%s&imdb=%s&tmdb=%s&tvdb=%s&art=%s,return)'
                        % (systvshowtitle, year, imdb, tmdb, tvdb, sysart))
            elif action in self.closing_actions:
                self.selected_items = None
                if self.hasVideo: self.execute_code('PlayerControl(Stop)')
                else: self.close()
        except:
            from resources.lib.modules import log_utils
            log_utils.error()
            self.close()
Esempio n. 53
0
 def clearCacheSearch(self):
     control.idle()
     if control.yesnoDialog(control.lang(32056).encode('utf-8'), '', ''):
         control.setSetting('tvsearch', '')
         control.setSetting('moviesearch', '')
         control.refresh()
Esempio n. 54
0
elif mode[0]=='bblogs':
    from resources.lib.modules import blog_viewer as bv
    wind = bv.Viewer('My first window')
    wind.doModal()
    del wind

###########################################################################################
elif mode[0]=='my_lists':
    lists = myLists.getLists()
    for ls in lists:
        addon.add_item({'mode': 'open_list', 'path':ls[1], 'name':ls[0]}, {'title': ls[0]}, img=icon_path('my_lists.jpg'), fanart=fanart, is_folder=True)
    addon.add_item({'mode':'add_list'},{'title':'[B][COLOR green]Add list...[/COLOR][/B]'},img=icon_path('my_lists.jpg'), fanart=fanart, is_folder=True)
    addon.end_of_directory()

elif mode[0]=='add_list':
    answ = control.yesnoDialog('Do you want to add local list or remote list?','', '' ,yeslabel='Remote',nolabel='Local')
    
    #remote
    if str(answ)=='1':
        path = control.get_keyboard('Enter list URL:')

        name = control.get_keyboard('Enter list title:')
        if path and name:
            good = client.request(path)
            if good:
                myLists.addList(name,path)
            else:
                control.infoDialog('Cannot connect to list.',heading='Castaway Lists')
        else:
            control.infoDialog('A problem occured. Try again!',heading='Castaway Lists')
Esempio n. 55
0
def authTrakt():
    if getTraktCredentialsInfo() == True:
        if control.yesnoDialog(
                control.lang(32511).encode('utf-8'),
                control.lang(32512).encode('utf-8'), '', 'Trakt'):
            control.setSetting(id='trakt.user', value='')
            control.setSetting(id='trakt.token', value='')
            control.setSetting(id='trakt.refresh', value='')
            return control.openSettings('2.12')
    username = control.setting(id='trakt.user')
    if username == '' or username == None:
        import xbmcgui
        username = xbmcgui.Dialog().input(heading="Trakt username",
                                          type=xbmcgui.INPUT_ALPHANUM)
        if username != '' and username != -1:
            control.setSetting(id='trakt.user', value=username)
    try:
        result = getTraktAsJson('/oauth/device/code',
                                {'client_id': V2_API_KEY})
        verification_url = (control.lang(32513) %
                            result['verification_url']).encode('utf-8')
        user_code = (control.lang(32514) % result['user_code']).encode('utf-8')
        expires_in = int(result['expires_in'])
        device_code = result['device_code']
        interval = result['interval']

        progressDialog = control.progressDialog
        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
                    })
                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 = client.request(urlparse.urljoin(BASE_URL, '/users/me'),
                                headers=headers)
        result = utils.json_loads_as_str(result)

        user = result['username']

        control.setSetting(id='trakt.user', value=user)
        control.setSetting(id='trakt.token', value=token)
        control.setSetting(id='trakt.refresh', value=refresh)
        raise Exception()
    except:
        control.openSettings('2.12')