Example #1
0
def deleteFavourite(meta, content):
    try:
        meta = json.loads(meta)
        if 'title' in meta: title = meta['title']
        if 'tvshowtitle' in meta: title = meta['tvshowtitle']

        try:
            dbcon = database.connect(control.favouritesFile)
            dbcur = dbcon.cursor()
            try:
                dbcur.execute("DELETE FROM %s WHERE id = '%s'" %
                              (content, meta['imdb']))
            except:
                pass
            try:
                dbcur.execute("DELETE FROM %s WHERE id = '%s'" %
                              (content, meta['tvdb']))
            except:
                pass
            dbcon.commit()
        except:
            pass

        control.refresh()
        control.infoDialog(control.lang(30412).encode('utf-8'), heading=title)
    except:
        return
Example #2
0
 def clearCacheAll(self):
     control.idle()
     yes = control.yesnoDialog(control.lang(32056).encode('utf-8'), '', '')
     if not yes: return
     from ptw.libraries import cache
     cache.cache_clear_all()
     control.infoDialog(control.lang(32057).encode('utf-8'), sound=True, icon='INFO')
Example #3
0
def addView(content):
    try:
        skin = control.skin
        record = (skin, content, str(control.getCurrentViewId()))
        control.makeFile(control.dataPath)
        dbcon = database.connect(control.viewsFile)
        dbcur = dbcon.cursor()
        dbcur.execute("CREATE TABLE IF NOT EXISTS views ("
                      "skin TEXT, "
                      "view_type TEXT, "
                      "view_id TEXT, "
                      "UNIQUE(skin, view_type)"
                      ");")
        dbcur.execute(
            "DELETE FROM views WHERE skin = '%s' AND view_type = '%s'" %
            (record[0], record[1]))
        dbcur.execute("INSERT INTO views Values (?, ?, ?)", record)
        dbcon.commit()

        viewName = control.infoLabel('Container.Viewmode')
        skinName = control.addon(skin).getAddonInfo('name')
        skinIcon = control.addon(skin).getAddonInfo('icon')

        control.infoDialog(viewName,
                           heading=skinName,
                           sound=True,
                           icon=skinIcon)
    except:
        return
Example #4
0
 def accountCheck(self):
     if traktCredentials == False and imdbCredentials == False:
         control.idle()
         control.infoDialog(control.lang(32042).encode('utf-8'),
                            sound=True,
                            icon='WARNING')
         sys.exit()
Example #5
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)')
Example #6
0
    def silent(self, url):
        control.idle()

        if not control.condVisibility(
                'Window.IsVisible(infodialog)') and not control.condVisibility(
                    'Player.HasVideo'):
            control.infoDialog(control.lang(32608).encode('utf-8'),
                               time=10000000)
            self.infoDialog = True
            self.silentDialog = 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 is True:
            self.silentDialog = False
            control.infoDialog("Trakt TV Show Sync Complete", time=1)
Example #7
0
 def infoCheck(self, version):
     try:
         control.infoDialog('',
                            control.lang(32074).encode('utf-8'),
                            time=5000,
                            sound=False)
         return '1'
     except:
         return '1'
Example #8
0
    def add(self, name, title, year, imdb, tmdb, range=False):
        if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo')\
                and self.silentDialog is False:
            control.infoDialog(control.lang(32552).encode('utf-8'),
                               time=10000000)
            self.infoDialog = True

        try:
            if not self.dupe_setting == 'true': raise Exception()

            id = [imdb, tmdb] if not tmdb == '0' else [imdb]
            lib = control.jsonrpc(
                '{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": {"filter":{"or": [{"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}]}, "properties" : ["imdbnumber", "originaltitle", "year"]}, "id": 1}'
                % (year, str(int(year) + 1), str(int(year) - 1)))
            lib = unicode(lib, 'utf-8', errors='ignore')
            lib = json.loads(lib)['result']['movies']
            lib = [
                i for i in lib
                if str(i['imdbnumber']) in id or (i['originaltitle'].encode(
                    'utf-8') == title and str(i['year']) == year)
            ][0]
        except:
            lib = []

        files_added = 0

        try:
            if not lib == []: raise Exception()

            if self.check_setting == 'true':
                src = lib_tools.check_sources(title, year, imdb, None, None,
                                              None, None, None)
                if not src: raise Exception()

            self.strmFile({
                'name': name,
                'title': title,
                'year': year,
                'imdb': imdb,
                'tmdb': tmdb
            })
            files_added += 1
        except:
            pass

        if range == True: return

        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') and files_added > 0:
            control.execute('UpdateLibrary(video)')
Example #9
0
def startDownload():
    if downloadPath == '':
        return control.infoDialog(
            'You need to set your download folder in addon settings first',
            'File Not Downloadable')

    control.execute('RunPlugin(%s?action=startDownloadThread)' % sys.argv[0])
Example #10
0
def removeDownload(url):
    try:

        def download():
            return []

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

        def download():
            return result

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

        control.refresh()
    except:
        control.infoDialog('You need to remove file manually',
                           'Can not remove from Queue')
Example #11
0
def addFavourite(meta, content, query):
    try:
        item = dict()
        meta = json.loads(meta)
        try:
            id = meta['imdb']
        except:
            id = meta['tvdb']

        if 'title' in meta: title = item['title'] = meta['title']
        if 'originaltitle' in meta:
            title = item['originaltitle'] = meta['originaltitle']
        if 'tvshowtitle' in meta: title = item['title'] = meta['tvshowtitle']
        if 'year' in meta: item['year'] = meta['year']
        if 'poster' in meta: item['poster'] = meta['poster']
        if 'fanart' in meta: item['fanart'] = meta['fanart']
        if 'imdb' in meta: item['imdb'] = meta['imdb']
        if 'tmdb' in meta: item['tmdb'] = meta['tmdb']
        if 'tvdb' in meta: item['tvdb'] = meta['tvdb']
        if 'tvrage' in meta: item['tvrage'] = meta['tvrage']

        control.makeFile(control.dataPath)
        dbcon = database.connect(control.favouritesFile)
        dbcur = dbcon.cursor()
        dbcur.execute("CREATE TABLE IF NOT EXISTS %s ("
                      "id TEXT, "
                      "items TEXT, "
                      "UNIQUE(id)"
                      ");" % content)
        dbcur.execute("DELETE FROM %s WHERE id = '%s'" % (content, id))
        dbcur.execute("INSERT INTO %s Values (?, ?)" % content,
                      (id, repr(item)))
        dbcon.commit()

        if query == None: control.refresh()
        control.infoDialog(control.lang(30411).encode('utf-8'), heading=title)
    except:
        return
Example #12
0
    def add(self, tvshowtitle, year, imdb, tvdb, range=False):
        if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo')\
                and self.silentDialog is False:
            control.infoDialog(control.lang(32552).encode('utf-8'),
                               time=10000000)
            self.infoDialog = True

        from resources.lib.indexers import episodes
        items = episodes.episodes().get(tvshowtitle,
                                        year,
                                        imdb,
                                        tvdb,
                                        idx=False)

        try:
            items = [{
                'title': i['title'],
                'year': i['year'],
                'imdb': i['imdb'],
                'tvdb': i['tvdb'],
                'season': i['season'],
                'episode': i['episode'],
                'tvshowtitle': i['tvshowtitle'],
                'premiered': i['premiered']
            } for i in items]
        except:
            items = []

        try:
            if not self.dupe_setting == 'true': raise Exception()
            if items == []: raise Exception()

            id = [items[0]['imdb'], items[0]['tvdb']]

            lib = control.jsonrpc(
                '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties" : ["imdbnumber", "title", "year"]}, "id": 1}'
            )
            lib = unicode(lib, 'utf-8', errors='ignore')
            lib = json.loads(lib)['result']['tvshows']
            lib = [
                i['title'].encode('utf-8') for i in lib
                if str(i['imdbnumber']) in id or (
                    i['title'].encode('utf-8') == items[0]['tvshowtitle']
                    and str(i['year']) == items[0]['year'])
            ][0]

            lib = control.jsonrpc(
                '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}'
                % lib)
            lib = unicode(lib, 'utf-8', errors='ignore')
            lib = json.loads(lib)['result']['episodes']
            lib = [
                'S%02dE%02d' % (int(i['season']), int(i['episode']))
                for i in lib
            ]

            items = [
                i for i in items if not 'S%02dE%02d' %
                (int(i['season']), int(i['episode'])) in lib
            ]
        except:
            pass

        files_added = 0

        for i in items:
            try:
                if xbmc.abortRequested == True: return sys.exit()

                if self.check_setting == 'true':
                    if i['episode'] == '1':
                        self.block = True
                        src = lib_tools.check_sources(i['title'], i['year'],
                                                      i['imdb'], i['tvdb'],
                                                      i['season'],
                                                      i['episode'],
                                                      i['tvshowtitle'],
                                                      i['premiered'])
                        if src: self.block = False
                    if self.block == True: raise Exception()

                premiered = i.get('premiered', '0')
                if (premiered != '0'
                        and int(re.sub('[^0-9]', '', str(premiered))) > int(
                            self.date)) or (premiered == '0'
                                            and not self.include_unknown):
                    continue

                self.strmFile(i)
                files_added += 1
            except:
                pass

        if range == True: return

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

        if self.library_setting == 'true' and not control.condVisibility(
                'Library.IsScanningVideo') and files_added > 0:
            control.execute('UpdateLibrary(video)')
Example #13
0
def download(name, image, url):

    from ptw.libraries import control

    if url == None:
        return control.infoDialog(control.lang(30501).encode('utf-8'))

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

    url = url.split('|')[0]

    content = re.compile('(.+?)\sS(\d*)E\d*$').findall(name)
    transname = name.translate(None, '\/:*?"<>|').strip('.')
    levels = ['../../../..', '../../..', '../..', '..']

    if len(content) == 0:
        dest = control.setting('movie_downloads')
        control.log('DEST M: |%s|%s|' % (dest, len(dest)))
        if len(dest) == 0:
            control.infoDialog(control.lang(33002).encode('utf-8'))
            control.openSettings('8.1')
            exit()
        dest = control.transPath(dest)
        for level in levels:
            try:
                control.makeFile(os.path.abspath(os.path.join(dest, level)))
            except:
                pass
        control.makeFile(dest)
        dest = os.path.join(dest, transname)
        control.makeFile(dest)
    else:
        dest = control.setting('tv_downloads')
        control.log('DEST TV: |%s|' % dest)
        if len(dest) == 0:
            control.infoDialog(control.lang(33002).encode('utf-8'))
            control.openSettings('8.2')
            exit()
        dest = control.transPath(dest)
        for level in levels:
            try:
                control.makeFile(os.path.abspath(os.path.join(dest, level)))
            except:
                pass
        control.makeFile(dest)
        transtvshowtitle = content[0][0].translate(None,
                                                   '\/:*?"<>|').strip('.')
        dest = os.path.join(dest, transtvshowtitle)
        control.makeFile(dest)
        dest = os.path.join(dest, 'Season %01d' % int(content[0][1]))
        control.makeFile(dest)

    ext = os.path.splitext(urlparse.urlparse(url).path)[1][1:]
    if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4'
    dest = os.path.join(dest, transname + '.' + ext)

    sysheaders = urllib.quote_plus(json.dumps(headers))

    sysurl = urllib.quote_plus(url)

    systitle = urllib.quote_plus(name)

    sysimage = urllib.quote_plus(image)

    sysdest = urllib.quote_plus(dest)

    script = inspect.getfile(inspect.currentframe())
    cmd = 'RunScript(%s, %s, %s, %s, %s, %s)' % (
        script, sysurl, sysdest, systitle, sysimage, sysheaders)

    xbmc.executebuiltin(cmd)
Example #14
0
def resolveUrl(name, url, audio, image, fanart, playable, content):
    try:
        if '.f4m' in url:
            label = cleantitle(name)
            ext = url.split('?')[0].split('&')[0].split('|')[0].rsplit(
                '.')[-1].replace('/', '').lower()
            if not ext == 'f4m': raise Exception()
            from resources.lib.libraries.f4mproxy.F4mProxy import f4mProxyHelper
            return f4mProxyHelper().playF4mLink(url, label, None, None, '',
                                                image)

        #legacy issue, will be removed later
        if 'afdah.org' in url and not '</source>' in url:
            url += '<source>afdah</source>'

        if '</source>' in url:
            source = re.compile('<source>(.+?)</source>').findall(url)[0]
            url = re.compile('(.+?)<source>').findall(url)[0]

            for i in ['_mv', '_tv', '_mv_tv']:
                try:
                    call = __import__(
                        'resources.lib.sources.%s%s' % (source, i), globals(),
                        locals(), ['object'], -1).source()
                except:
                    pass

            from resources.lib import sources
            d = sources.sources()

            url = call.get_sources(url, d.hosthdfullDict, d.hostsdfullDict,
                                   d.hostlocDict)

            if type(url) == list and len(url) == 1:
                url = url[0]['url']

            elif type(url) == list:
                url = sorted(url, key=lambda k: k['quality'])
                for i in url:
                    i.update(
                        (k, '720p') for k, v in i.iteritems() if v == 'HD')
                for i in url:
                    i.update(
                        (k, '480p') for k, v in i.iteritems() if v == 'SD')
                q = [
                    '[B]%s[/B] | %s' %
                    (i['source'].upper(), i['quality'].upper()) for i in url
                ]
                u = [i['url'] for i in url]
                select = control.selectDialog(q)
                if select == -1: return
                url = u[select]

            url = call.resolve(url)

        from resources.lib import resolvers
        host = (urlparse.urlparse(url).netloc).rsplit('.',
                                                      1)[0].rsplit('.')[-1]
        url = resolvers.request(url)

        if type(url) == list and len(url) == 1:
            url = url[0]['url']

        elif type(url) == list:
            url = sorted(url, key=lambda k: k['quality'])
            for i in url:
                i.update((k, '720p') for k, v in i.iteritems() if v == 'HD')
            for i in url:
                i.update((k, '480p') for k, v in i.iteritems() if v == 'SD')
            q = [
                '[B]%s[/B] | %s' % (host.upper(), i['quality'].upper())
                for i in url
            ]
            u = [i['url'] for i in url]
            select = control.selectDialog(q)
            if select == -1: return
            url = u[select]

        if url == None: raise Exception()
    except:
        return control.infoDialog(control.lang(30705).encode('utf-8'))
        pass

    if playable == 'true':
        item = control.item(path=url)
        return control.resolve(int(sys.argv[1]), True, item)
    else:
        label = cleantitle(name)
        item = control.item(path=url, iconImage=image, thumbnailImage=image)
        item.setInfo(type='Video', infoLabels={'title': label})
        control.playlist.clear()
        control.player.play(url, item)
Example #15
0
def nhlStreams(name, url):
    try:
        name = re.sub('\s\[COLOR.+?\].+?\[/COLOR\]', '', name).strip()
        n1 = name + ' [COLOR gold]%s[/COLOR]' ; n2 = name + ' [COLOR red]%s[/COLOR]'

        selectHomeGame = 'x0xe%sx0xehome' % str(url)
        selectAwayGame = 'x0xe%sx0xeaway' % str(url)

        url = re.compile('(\d{4})(\d{2})(\d{4})').findall(url)[0]
        url = 'http://smb.cdnak.neulion.com/fs/nhl/mobile/feed_new/data/streams/%s/ipad/%s_%s.json' % (url[0], url[1], url[2])

        result = client.request(url)
        result = json.loads(result)

        items = result['gameStreams']['ipad']
        h = items['home'] ; a = items['away']
    except:
        pass

    l1 = []; l2 = []

    try: finish = result['finish']
    except: finish = 'true'

    try: image = re.compile('"image" *: *"(.+?)"').findall(json.dumps(h))[-1]
    except: image = '0'

    try: l1.append({'name': n1 % 'Home LIVE', 'url': h['live']['bitrate0'] + selectHomeGame, 'image': image})
    except: pass

    try: l2.append({'name': n2 % 'Home Whole', 'url': h['vod-whole']['bitrate0'], 'image': image})
    except: pass

    try: l2.append({'name': n2 % 'Home Continuous', 'url': h['vod-continuous']['bitrate0'], 'image': image})
    except: pass

    try: l2.append({'name': n2 % 'Home Condensed', 'url': h['vod-condensed']['bitrate0'], 'image': image})
    except: pass

    try: image = re.compile('"image" *: *"(.+?)"').findall(json.dumps(a))[-1]
    except: image = '0'

    try: l1.append({'name': n1 % 'Away LIVE', 'url': a['live']['bitrate0'] + selectAwayGame, 'image': image})
    except: pass

    try: l2.append({'name': n2 % 'Away Whole', 'url': a['vod-whole']['bitrate0'], 'image': image})
    except: pass

    try: l2.append({'name': n2 % 'Away Continuous', 'url': a['vod-continuous']['bitrate0'], 'image': image})
    except: pass

    try: l2.append({'name': n2 % 'Away Condensed', 'url': a['vod-condensed']['bitrate0'], 'image': image})
    except: pass

    if finish == 'false':
        for i in l1: addDirectoryItem(i['name'], i['url'], 'nhlResolve', i['image'], '0', isFolder=False)
    else:
        for i in l2: addDirectoryItem(i['name'], i['url'], 'nhlResolve', i['image'], '0', isFolder=False)

    if l1 == [] and l2 == []:
        return control.infoDialog(control.lang(30755).encode('utf-8'), name, addonIcon)

    endDirectory()
Example #16
0
    def run(self):
        def download():
            return []

        result = cache.bennu_download_get(download, 600000000, table='rel_dl')

        for item in result:
            self.name = item['name']
            self.image = item['image']
            self.url = item['url']

            sysname = self.name.translate(None, '\/:*?"<>|').strip('.')

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

            ext = os.path.splitext(urlparse.urlparse(url).path)[1][1:].lower()

            hdlr = re.compile('.+? ([(]\d{4}[)]|S\d*E\d*)$').findall(self.name)
            if len(hdlr) == 0: self.content = 'Uncategorised'

            if ext in ['m4a', 'mp3', 'aac']: self.content = 'Music'

            hdlr = re.compile('.+? (S\d*E\d*)$').findall(self.name)
            if len(hdlr) > 0: self.content = 'TVShows'

            hdlr = re.compile('.+? [(](\d{4})[)]$').findall(self.name)
            if len(hdlr) > 0: self.content = 'Movies'

            if self.content == 'Movies':
                dest = os.path.join(downloadPath, self.content)
                control.makeFile(dest)
                dest = os.path.join(dest, sysname)
                control.makeFile(dest)

            elif self.content == 'TVShows':
                d = re.compile('(.+?) S(\d*)E(\d*)$').findall(sysname)[0]
                dest = os.path.join(downloadPath, self.content)
                control.makeFile(dest)
                dest = os.path.join(dest, d[0])
                control.makeFile(dest)
                dest = os.path.join(dest, 'Season %01d' % int(d[1]))
                control.makeFile(dest)

            else:
                dest = os.path.join(downloadPath, self.content)
                control.makeFile(dest)

            if not ext in [
                    'mp4', 'm4a', 'mp3', 'aac', 'mkv', 'flv', 'avi', 'mpg'
            ]:
                ext = 'mp4'

            dest = os.path.join(dest, sysname + '.' + ext)

            control.infoDialog(self.name + ' Is Downloading',
                               'Downloads Started',
                               self.image,
                               time=7000)

            try:
                req = urllib2.Request(url, headers=headers)
                resp = urllib2.urlopen(req, timeout=30)
            except Exception, e:
                removeDownload(self.url)
                print '%s ERROR - File Failed To Open' % (dest)
                continue

            try:
                self.size = int(resp.headers['Content-Length'])
            except:
                self.size = 0

            if self.size < 1:
                removeDownload(self.url)
                print '%s Unknown filesize - Unable to download' % (dest)
                continue

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

            size = 1024 * 1024
            if self.size < size: size = self.size

            gb = '%.2f GB' % (float(self.size) / 1073741824)

            start = time.clock()

            total = 0
            notify = 0
            errors = 0
            count = 0
            resume = 0
            sleep = 0

            self.clear()

            control.window.setProperty(property + '.status', 'downloading')
            control.window.setProperty(property + '.name', str(self.name))
            control.window.setProperty(property + '.image', str(self.image))
            control.window.setProperty(property + '.size', str(gb))

            f = control.openFile(dest, 'wb')

            chunk = None
            chunks = []

            while True:
                downloaded = total
                for c in chunks:
                    downloaded += len(c)

                percent = min(100 * downloaded / self.size, 100)

                self.speed = str(
                    int((downloaded / 1024) /
                        (time.clock() - start))) + ' KB/s'
                self.percent = str(percent) + '%'

                control.window.setProperty(property + '.percent',
                                           str(self.percent))
                control.window.setProperty(property + '.speed',
                                           str(self.speed))

                if percent >= notify:
                    control.infoDialog('Downloaded %s' % self.percent,
                                       self.name,
                                       self.image,
                                       time=5000)
                    notify += 10

                chunk = None
                error = False

                try:
                    chunk = resp.read(size)
                    if not chunk:
                        if self.percent < 99:
                            error = True
                        else:
                            while len(chunks) > 0:
                                c = chunks.pop(0)
                                f.write(c)
                                del c

                            f.close()
                            print '%s download complete' % (dest)
                            break

                except Exception, e:
                    print str(e)
                    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
                    print '%d Error(s) whilst downloading %s' % (count, dest)
                    control.sleep(sleep * 1000)

                if (resumable and errors > 0) or errors >= 10:
                    if (not resumable and resume >= 50) or resume >= 500:
                        #Give up!
                        print '%s download canceled - too many error whilst downloading' % (
                            dest)
                        break

                    resume += 1
                    errors = 0
                    if resumable:
                        chunks = []
                        #create new response
                        print 'Download resumed (%d) %s' % (resume, dest)
                        h = headers
                        h['Range'] = 'bytes=%d-' % int(total)
                        try:
                            resp = urllib2.urlopen(urllib2.Request(url,
                                                                   headers=h),
                                                   timeout=10)
                        except:
                            resp = None
                    else:
                        #use existing response
                        pass

                if control.window.getProperty(property + '.status') == 'stop':
                    control.infoDialog('Process Complete',
                                       'Downloads',
                                       time=5000)
                    return self.clear()
Example #17
0
                     rlist[rand]['title'])
             except:
                 pass
         else:
             try:
                 r += '&' + p + '=' + urllib.quote_plus(rlist[rand][p])
             except:
                 pass
     try:
         r += '&meta=' + urllib.quote_plus(json.dumps(rlist[rand]))
     except:
         r += '&meta=' + urllib.quote_plus("{}")
     if rtype == "movie":
         try:
             control.infoDialog(rlist[rand]['title'],
                                control.lang(32536).encode('utf-8'),
                                time=30000)
         except:
             pass
     elif rtype == "episode":
         try:
             control.infoDialog(rlist[rand]['tvshowtitle'] + " - Season " +
                                rlist[rand]['season'] + " - " +
                                rlist[rand]['title'],
                                control.lang(32536).encode('utf-8'),
                                time=30000)
         except:
             pass
     control.execute('RunPlugin(%s)' % r)
 except:
     control.infoDialog(control.lang(32537).encode('utf-8'), time=8000)
Example #18
0
def manager(name, imdb, tvdb, content):
    try:
        post = {
            "movies": [{
                "ids": {
                    "imdb": imdb
                }
            }]
        } if content == 'movie' else {
            "shows": [{
                "ids": {
                    "tvdb": tvdb
                }
            }]
        }

        items = [(control.lang(32516).encode('utf-8'), '/sync/collection')]
        items += [(control.lang(32517).encode('utf-8'),
                   '/sync/collection/remove')]
        items += [(control.lang(32518).encode('utf-8'), '/sync/watchlist')]
        items += [(control.lang(32519).encode('utf-8'),
                   '/sync/watchlist/remove')]
        items += [(control.lang(32520).encode('utf-8'),
                   '/users/me/lists/%s/items')]

        result = getTraktAsJson('/users/me/lists')
        lists = [(i['name'], i['ids']['slug']) for i in result]
        lists = [lists[i // 2] for i in range(len(lists) * 2)]
        for i in range(0, len(lists), 2):
            lists[i] = ((control.lang(32521) % lists[i][0]).encode('utf-8'),
                        '/users/me/lists/%s/items' % lists[i][1])
        for i in range(1, len(lists), 2):
            lists[i] = ((control.lang(32522) % lists[i][0]).encode('utf-8'),
                        '/users/me/lists/%s/items/remove' % lists[i][1])
        items += lists

        select = control.selectDialog([i[0] for i in items],
                                      control.lang(32515).encode('utf-8'))

        if select == -1:
            return
        elif select == 4:
            t = control.lang(32520).encode('utf-8')
            k = control.keyboard('', t)
            k.doModal()
            new = k.getText() if k.isConfirmed() else None
            if (new == None or new == ''): return
            result = __getTrakt('/users/me/lists',
                                post={
                                    "name": new,
                                    "privacy": "private"
                                })[0]

            try:
                slug = utils.json_loads_as_str(result)['ids']['slug']
            except:
                return control.infoDialog(control.lang(32515).encode('utf-8'),
                                          heading=str(name),
                                          sound=True,
                                          icon='ERROR')
            result = __getTrakt(items[select][1] % slug, post=post)[0]
        else:
            result = __getTrakt(items[select][1], post=post)[0]

        icon = control.infoLabel(
            'ListItem.Icon') if not result == None else 'ERROR'

        control.infoDialog(control.lang(32515).encode('utf-8'),
                           heading=str(name),
                           sound=True,
                           icon=icon)
    except:
        return
Example #19
0
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)
Example #20
0
def get(name, imdb, season, episode):
    try:
        langs = []
        try:
            try: langs = langDict[control.setting('sublang1')].split(',')
            except: langs.append(langDict[control.setting('sublang1')])
        except: pass
        try:
            try: langs = langs + langDict[control.setting('sublang2')].split(',')
            except: langs.append(langDict[control.setting('sublang2')])
        except: pass

        try: subLang = xbmc.Player().getSubtitles()
        except: subLang = ''
        if subLang == langs[0]: raise Exception()
        control.log('SUBS XXXXXX:%s' % name)

        server = xmlrpclib.Server('http://api.opensubtitles.org/xml-rpc', verbose=0)

        data = server.LogIn( control.setting('OSuser').strip(),  control.setting('OSpass').strip(), 'en', subsversion)
        token = data['token']
        if data['status'] !='200 OK':
            control.log("SUBS: Token %s, Status: %s" % (data['status'], data))
            control.infoDialog('Open Subtitles Error: ' + str(data['status']), "Open Subtitles ERROR", time=6000)
            #control.dialog.ok(control.addonInfo('name'), str('Open Subtitles error[CR]Check login and password in settings[CR][CR]Error: %s'% data['status']), '')

        sublanguageid = ','.join(langs) ; imdbid = re.sub('[^0-9]', '', imdb)

        if not (season == '' or episode == ''):
            result = server.SearchSubtitles(token, [{'sublanguageid': sublanguageid, 'imdbid': imdbid, 'season': season, 'episode': episode}])['data']
            fmt = ['hdtv']
        else:
            result = server.SearchSubtitles(token, [{'sublanguageid': sublanguageid, 'imdbid': imdbid}])['data']
            try: vidPath = xbmc.Player().getPlayingFile()
            except: vidPath = ''
            fmt = re.split('\.|\(|\)|\[|\]|\s|\-', vidPath)
            fmt = [i.lower() for i in fmt]
            fmt = [i for i in fmt if i in quality]

        filter = []
        result = [i for i in result if i['SubSumCD'] == '1']

        for lang in langs:
            filter += [i for i in result if i['SubLanguageID'] == lang and any(x in i['MovieReleaseName'].lower() for x in fmt)]
            filter += [i for i in result if i['SubLanguageID'] == lang and any(x in i['MovieReleaseName'].lower() for x in quality)]
            filter += [i for i in result if i['SubLanguageID'] == lang]

        try: lang = xbmc.convertLanguage(filter[0]['SubLanguageID'], xbmc.ISO_639_1)
        except: lang = filter[0]['SubLanguageID']

        content = [filter[0]['IDSubtitleFile'],]
        content = server.DownloadSubtitles(token, content)
        content = base64.b64decode(content['data'][0]['data'])
        content = str(zlib.decompressobj(16+zlib.MAX_WBITS).decompress(content))

        subtitle = xbmc.translatePath('special://temp/')
        subtitle = os.path.join(subtitle, 'TemporarySubs.%s.srt' % lang)

        codepage = codePageDict.get(lang, '')
        if codepage and control.setting('autoconvert_utf8') == 'true':
            try:
                content_encoded = codecs.decode(content, codepage)
                content = codecs.encode(content_encoded, 'utf-8')
            except:
                pass

        file = control.openFile(subtitle, 'w')
        file.write(str(content))
        file.close()

        xbmc.sleep(1000)
        xbmc.Player().setSubtitles(subtitle)
    except Exception as e:
        control.log('SUBS: Error %s' %e)
        pass
Example #21
0
    def update(self, query=None, info='true'):
        if not query == None: control.idle()

        try:

            items = []
            season, episode = [], []
            show = [
                os.path.join(self.library_folder, i)
                for i in control.listDir(self.library_folder)[0]
            ]
            for s in show:
                try:
                    season += [
                        os.path.join(s, i) for i in control.listDir(s)[0]
                    ]
                except:
                    pass
            for s in season:
                try:
                    episode.append([
                        os.path.join(s, i) for i in control.listDir(s)[1]
                        if i.endswith('.strm')
                    ][-1])
                except:
                    pass

            for file in episode:
                try:
                    file = control.openFile(file)
                    read = file.read()
                    read = read.encode('utf-8')
                    file.close()

                    if not read.startswith(sys.argv[0]): raise Exception()

                    params = dict(urlparse.parse_qsl(read.replace('?', '')))

                    try:
                        tvshowtitle = params['tvshowtitle']
                    except:
                        tvshowtitle = None
                    try:
                        tvshowtitle = params['show']
                    except:
                        pass
                    if tvshowtitle == None or tvshowtitle == '':
                        raise Exception()

                    year, imdb, tvdb = params['year'], params['imdb'], params[
                        'tvdb']

                    imdb = 'tt' + re.sub('[^0-9]', '', str(imdb))

                    try:
                        tmdb = params['tmdb']
                    except:
                        tmdb = '0'

                    items.append({
                        'tvshowtitle': tvshowtitle,
                        'year': year,
                        'imdb': imdb,
                        'tmdb': tmdb,
                        'tvdb': tvdb
                    })
                except:
                    pass

            items = [i for x, i in enumerate(items) if i not in items[x + 1:]]
            if len(items) == 0: raise Exception()
        except:
            return

        try:
            lib = control.jsonrpc(
                '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties" : ["imdbnumber", "title", "year"]}, "id": 1}'
            )
            lib = unicode(lib, 'utf-8', errors='ignore')
            lib = json.loads(lib)['result']['tvshows']
        except:
            return

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

        try:
            control.makeFile(control.dataPath)
            dbcon = database.connect(control.libcacheFile)
            dbcur = dbcon.cursor()
            dbcur.execute("CREATE TABLE IF NOT EXISTS tvshows ("
                          "id TEXT, "
                          "items TEXT, "
                          "UNIQUE(id)"
                          ");")
        except:
            return

        try:
            from resources.lib.indexers import episodes
        except:
            return

        files_added = 0

        # __init__ doesn't get called from services so self.date never gets updated and new episodes are not added to the library
        self.datetime = (datetime.datetime.utcnow() -
                         datetime.timedelta(hours=5))
        self.date = (self.datetime -
                     datetime.timedelta(hours=24)).strftime('%Y%m%d')

        for item in items:
            it = None

            if xbmc.abortRequested == True: return sys.exit()

            try:
                dbcur.execute("SELECT * FROM tvshows WHERE id = '%s'" %
                              item['tvdb'])
                fetch = dbcur.fetchone()
                it = eval(fetch[1].encode('utf-8'))
            except:
                pass

            try:
                if not it == None: raise Exception()

                it = episodes.episodes().get(item['tvshowtitle'],
                                             item['year'],
                                             item['imdb'],
                                             item['tvdb'],
                                             idx=False)

                status = it[0]['status'].lower()

                it = [{
                    'title': i['title'],
                    'year': i['year'],
                    'imdb': i['imdb'],
                    'tvdb': i['tvdb'],
                    'season': i['season'],
                    'episode': i['episode'],
                    'tvshowtitle': i['tvshowtitle'],
                    'premiered': i['premiered']
                } for i in it]

                if status == 'continuing': raise Exception()
                dbcur.execute("INSERT INTO tvshows Values (?, ?)",
                              (item['tvdb'], repr(it)))
                dbcon.commit()
            except:
                pass

            try:
                id = [item['imdb'], item['tvdb']]
                if not item['tmdb'] == '0': id += [item['tmdb']]

                ep = [
                    x['title'].encode('utf-8') for x in lib
                    if str(x['imdbnumber']) in id or (
                        x['title'].encode('utf-8') == item['tvshowtitle']
                        and str(x['year']) == item['year'])
                ][0]
                ep = control.jsonrpc(
                    '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}'
                    % ep)
                ep = unicode(ep, 'utf-8', errors='ignore')
                ep = json.loads(ep).get('result', {}).get('episodes', {})
                ep = [{
                    'season': int(i['season']),
                    'episode': int(i['episode'])
                } for i in ep]
                ep = sorted(ep, key=lambda x: (x['season'], x['episode']))[-1]

                num = [
                    x for x, y in enumerate(it)
                    if str(y['season']) == str(ep['season'])
                    and str(y['episode']) == str(ep['episode'])
                ][-1]
                it = [y for x, y in enumerate(it) if x > num]
                if len(it) == 0: continue
            except:
                continue

            for i in it:
                try:
                    if xbmc.abortRequested == True: return sys.exit()

                    premiered = i.get('premiered', '0')
                    if (premiered != '0'
                            and int(re.sub('[^0-9]', '', str(premiered))) >
                            int(self.date)) or (premiered == '0'
                                                and not self.include_unknown):
                        continue

                    libtvshows().strmFile(i)
                    files_added += 1
                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') and files_added > 0:
            control.execute('UpdateLibrary(video)')
Example #22
0
                        pass

                if control.window.getProperty(property + '.status') == 'stop':
                    control.infoDialog('Process Complete',
                                       'Downloads',
                                       time=5000)
                    return self.clear()

            self.clear()

            control.infoDialog(self.name + ' Completed',
                               'Download Complete',
                               self.image,
                               time=5000)
            removeDownload(self.url)

        control.infoDialog('Process Complete', 'Downloads', time=5000)
        return

    def kill(self):
        control.window.setProperty(property + '.status', 'stop')

    def clear(self):
        control.window.clearProperty(property + '.status')
        control.window.clearProperty(property + '.name')
        control.window.clearProperty(property + '.image')
        control.window.clearProperty(property + '.percent')
        control.window.clearProperty(property + '.speed')
        control.window.clearProperty(property + '.size')
        control.refresh()