Exemplo n.º 1
0
    def write_file(path, content):
        try:
            path = xbmc.makeLegalFilename(path)
            if not isinstance(content, basestring):
                content = str(content)

            file = control.openFile(path, 'w')
            file.write(str(content))
            file.close()
        except Exception as e:
            pass
Exemplo n.º 2
0
def keyboard(response):
    try:
        i = os.path.join(control.dataPath, 'img')
        f = control.openFile(i, 'w')
        f.write(client.request(response))
        f.close()
        f = control.image(450, 5, 375, 115, i)
        d = control.windowDialog
        d.addControl(f)
        control.deleteFile(i)
        d.show()
        t = 'Type the letters in the image'
        k = control.keyboard('', t)
        k.doModal()
        c = k.getText() if k.isConfirmed() else None
        if c == '': c = None
        d.removeControl(f)
        d.close()
        return c
    except:
        return
Exemplo n.º 3
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)')
Exemplo n.º 4
0
def getDirectory(name,
                 url,
                 audio,
                 image,
                 fanart,
                 playable,
                 content,
                 close=True,
                 local=False):
    if local == True:
        f = control.openFile(url)
        result = f.read()
        f.close()
    else:
        result = cache.get(client.request, 0, url)

    result = str(result).replace('\r', '').replace('\n', '').replace(
        '\t', '').replace(' ', '')

    try:
        fanart = re.findall('<fanart>(.+?)</fanart>', result)[0]
    except:
        fanart = '0'

    try:
        notify = re.compile('<notify>(.+?)</notify>').findall(result)[0]

        vip = re.findall('<poster>(.+?)</poster>', result)[0]
        if not re.search('[a-zA-Z]', vip): raise Exception()

        def message(vip):
            return (vip + version)

        check = cache.get(message, 600000000, vip, table='rel_vip')

        version = re.findall('<new>(.+?)</new>', notify)[0]
        if not version.isdigit(): raise Exception()

        if check == (vip + version): raise Exception()

        title = '[B]Announcement From %s![/B]' % vip
        msg1 = re.findall('<message1>(.+?)</message1>', notify)[0]
        msg2 = re.findall('<message2>(.+?)</message2>', notify)[0]
        msg3 = re.findall('<message3>(.+?)</message3>', notify)[0]

        check = cache.get(message, 0, vip, table='rel_vip')

        control.dialog.ok(str(title), str(msg1), str(msg2), str(msg3))
    except:
        pass

    infos = re.compile('<info>(.+?)</info>').findall(result)

    for info in infos:
        try:
            name = re.findall('<message>(.+?)</message>', info)[0]

            try:
                image = re.findall('<thumbnail>(.+?)</thumbnail>', info)[0]
            except:
                image = '0'

            addDirectoryItem(name, '0', '0', image, image, fanart, '0', '0',
                             {})
        except:
            pass

    popups = re.compile('<popup>(.+?)</popup>').findall(result)

    for popup in popups:
        try:
            name = re.findall('<name>(.+?)</name>', popup)[0]

            url = re.findall('<popImage>(.+?)</popImage>', popup)[0]

            try:
                image = re.findall('<thumbnail>(.+?)</thumbnail>', popup)[0]
            except:
                image = '0'

            try:
                audio = re.findall('<sound>(.+?)</sound>', popup)[0]
            except:
                audio = '0'

            addDirectoryItem(name, url, 'openDialog', image, image, fanart,
                             audio, '0', {})
        except:
            pass

    special = re.compile(
        '<name>([^<]+)</name><link>([^<]+)</link><thumbnail>([^<]+)</thumbnail><date>([^<]+)</date>'
    ).findall(result)
    for name, url, image, date in special:
        if re.search(r'\d+', date):
            name += ' [COLOR red] Updated %s[/COLOR]' % date
        addDirectoryItem(name, url, 'ndmode', image, image, fanart, '0', '0',
                         {})

    special = re.compile(
        '<name>([^<]+)</name><link>([^<]+)</link><thumbnail>([^<]+)</thumbnail><mode>([^<]+)</mode>'
    ).findall(result)
    for name, url, image, action in special:
        addDirectoryItem(name, url, action, image, image, fanart, '0', '0', {})

    meta = False

    try:
        content = re.findall('<meta>(.+?)</meta>', result)[0]
    except:
        content = '0'

    try:
        tvshow = re.findall('<tvshow>(.+?)</tvshow>', result)[0]
    except:
        tvshow = '0'

    if content in ['seasons', 'episodes'] and tvshow == '0':
        content = '0'

    if content in ['movies', 'tvshows'] and control.setting('meta') == 'true':
        try:
            from metahandler import metahandlers
            metaget = metahandlers.MetaData(preparezip=False)
            meta = True
        except:
            meta = False

    elif content in ['seasons', 'episodes']:
        try:
            from metahandler import metahandlers
            metaget = metahandlers.MetaData(preparezip=False)
            #tvd = metaget.get_meta('tvshow', tvshow)
            tvd = cachemeta.get(metaget.get_meta, 24, 'tvshow', tvshow, '', '',
                                '')
        except:
            tvd = {}

    dirs = re.compile('<dir>(.+?)</dir>').findall(result)

    totalItems = len(dirs)

    for dir in dirs:
        try:
            data = {}

            name = re.findall('<name>(.+?)</name>', dir)[0]

            url = re.findall('<link>(.+?)</link>', dir)[0]

            try:
                image = re.findall('<thumbnail>(.+?)</thumbnail>', dir)[0]
            except:
                image = '0'

            try:
                fanart2 = re.findall('<fanart>(.+?)</fanart>', dir)[0]
            except:
                fanart2 = fanart

            if meta == True and content == 'tvshows':
                try:
                    title = cleantitle(name).encode('utf-8')
                    data = {'title': title, 'tvshowtitle': title}

                    #data = metaget.get_meta('tvshow', title)
                    data = cachemeta.get(metaget.get_meta, 24, 'tvshow', title,
                                         '', '', '')

                    metafanart = data['backdrop_url']
                    if not metafanart == '': fanart2 = metafanart
                except:
                    pass

            elif content == 'tvshows':
                try:
                    title = cleantitle(name).encode('utf-8')
                    data = {'title': title, 'tvshowtitle': title}
                except:
                    pass

            elif content == 'seasons':
                try:
                    title = cleantitle(tvshow).encode('utf-8')
                    data = {'title': title, 'tvshowtitle': title}

                    data.update(tvd)

                    metafanart = tvd['backdrop_url']
                    if not metafanart == '': fanart2 = metafanart
                except:
                    pass

            addDirectoryItem(name,
                             url,
                             'ndmode',
                             image,
                             image,
                             fanart2,
                             '0',
                             content,
                             data,
                             totalItems=totalItems)
        except:
            pass

    items = re.compile('<item>(.+?)</item>').findall(result)

    try:
        sort = re.findall('<sort>(.+?)</sort>', result)[0]
    except:
        sort = ''
    if sort == 'yes': items = sorted(items)
    totalItems = len(items)

    for item in items:
        try:

            data = {}

            name = re.findall('<title>(.+?)</title>', item)[0]

            url = re.findall('<link>(.+?)</link>', item)[0]

            try:
                image = image2 = re.findall('<thumbnail>(.+?)</thumbnail>',
                                            item)[0]
            except:
                image = image2 = '0'

            try:
                fanart2 = re.findall('<fanart>(.+?)</fanart>', item)[0]
            except:
                fanart2 = fanart

            if meta == True and content == 'movies':
                try:
                    title = cleantitle(name).encode('utf-8')
                    data = {'title': title}

                    title, year = re.compile('(.+?)[(](\d{4})[)]').findall(
                        name)[0]
                    title = cleantitle(title).encode('utf-8')
                    data = {'title': title, 'year': year}

                    #data = metaget.get_meta('movie', title, year=year)
                    data = cachemeta.get(metaget.get_meta, 24, 'movie', title,
                                         '', '', year)

                    metaimage = data['cover_url']
                    if not metaimage == '': image = metaimage
                    metafanart = data['backdrop_url']
                    if not metafanart == '': fanart2 = metafanart
                except:
                    pass

            elif content == 'movies':
                try:
                    title = cleantitle(name).encode('utf-8')
                    data = {'title': title}

                    title, year = re.compile('(.+?)[(](\d{4})[)]').findall(
                        name)[0]
                    title = cleantitle(title).encode('utf-8')
                    data = {'title': title, 'year': year}
                except:
                    pass

            elif content == 'episodes':
                try:
                    title = cleantitle(name).encode('utf-8')
                    data = {'title': title, 'tvshowtitle': tvshow}
                except:
                    pass
                try:
                    i = cleaneptitle(tvshow, title)
                    title, season, episode = i[0].encode('utf-8'), i[1], i[2]
                    data = {
                        'title': title,
                        'tvshowtitle': tvshow,
                        'season': season,
                        'episode': episode
                    }
                except:
                    pass
                try:
                    data.update({
                        'year': tvd['year'],
                        'imdb_id': tvd['imdb_id'],
                        'tvdb_id': tvd['tvdb_id'],
                        'tvshowtitle': tvd['TVShowTitle'],
                        'genre': tvd['genre'],
                        'studio': tvd['studio'],
                        'status': tvd['status'],
                        'duration': tvd['duration'],
                        'rating': tvd['rating'],
                        'mpaa': tvd['mpaa'],
                        'plot': tvd['plot'],
                        'cast': tvd['cast']
                    })

                    metafanart = tvd['backdrop_url']
                    if not metafanart == '': image = fanart2 = metafanart
                except:
                    pass

            if 'sublink' in url:
                addDirectoryItem(name,
                                 url,
                                 'subDirectory',
                                 image,
                                 image2,
                                 fanart2,
                                 '0',
                                 content,
                                 data,
                                 tvshow=tvshow,
                                 totalItems=totalItems,
                                 isFolder=True)
            else:
                addDirectoryItem(name,
                                 url,
                                 'resolveUrl',
                                 image,
                                 image2,
                                 fanart2,
                                 '0',
                                 content,
                                 data,
                                 totalItems=totalItems,
                                 isFolder=False)
        except:
            pass

    endDirectory(content, close)
Exemplo n.º 5
0
    def get(self, name, imdb, season, episode):
        try:
            if not control.setting('subtitles') == 'true': raise Exception()


            langDict = {'Afrikaans': 'afr', 'Albanian': 'alb', 'Arabic': 'ara', 'Armenian': 'arm', 'Basque': 'baq', 'Bengali': 'ben', 'Bosnian': 'bos', 'Breton': 'bre', 'Bulgarian': 'bul', 'Burmese': 'bur', 'Catalan': 'cat', 'Chinese': 'chi', 'Croatian': 'hrv', 'Czech': 'cze', 'Danish': 'dan', 'Dutch': 'dut', 'English': 'eng', 'Esperanto': 'epo', 'Estonian': 'est', 'Finnish': 'fin', 'French': 'fre', 'Galician': 'glg', 'Georgian': 'geo', 'German': 'ger', 'Greek': 'ell', 'Hebrew': 'heb', 'Hindi': 'hin', 'Hungarian': 'hun', 'Icelandic': 'ice', 'Indonesian': 'ind', 'Italian': 'ita', 'Japanese': 'jpn', 'Kazakh': 'kaz', 'Khmer': 'khm', 'Korean': 'kor', 'Latvian': 'lav', 'Lithuanian': 'lit', 'Luxembourgish': 'ltz', 'Macedonian': 'mac', 'Malay': 'may', 'Malayalam': 'mal', 'Manipuri': 'mni', 'Mongolian': 'mon', 'Montenegrin': 'mne', 'Norwegian': 'nor', 'Occitan': 'oci', 'Persian': 'per', 'Polish': 'pol', 'Portuguese': 'por,pob', 'Portuguese(Brazil)': 'pob,por', 'Romanian': 'rum', 'Russian': 'rus', 'Serbian': 'scc', 'Sinhalese': 'sin', 'Slovak': 'slo', 'Slovenian': 'slv', 'Spanish': 'spa', 'Swahili': 'swa', 'Swedish': 'swe', 'Syriac': 'syr', 'Tagalog': 'tgl', 'Tamil': 'tam', 'Telugu': 'tel', 'Thai': 'tha', 'Turkish': 'tur', 'Ukrainian': 'ukr', 'Urdu': 'urd'}

            codePageDict = {'ara': 'cp1256', 'ar': 'cp1256', 'ell': 'cp1253', 'el': 'cp1253', 'heb': 'cp1255', 'he': 'cp1255', 'tur': 'cp1254', 'tr': 'cp1254', 'rus': 'cp1251', 'ru': 'cp1251'}

            quality = ['bluray', 'hdrip', 'brrip', 'bdrip', 'dvdrip', 'webrip', 'hdtv']


            langs = []
            try:
                try: langs = langDict[control.setting('subtitles.lang.1')].split(',')
                except: langs.append(langDict[control.setting('subtitles.lang.1')])
            except: pass
            try:
                try: langs = langs + langDict[control.setting('subtitles.lang.2')].split(',')
                except: langs.append(langDict[control.setting('subtitles.lang.2')])
            except: pass

            try: subLang = xbmc.Player().getSubtitles()
            except: subLang = ''
            if subLang == langs[0]: raise Exception()

            server = xmlrpclib.Server('http://api.opensubtitles.org/xml-rpc', verbose=0)
            token = server.LogIn('', '', 'en', 'XBMC_Subtitles_v1')['token']

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

            if not (season == None or episode == None):
                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 = gzip.GzipFile(fileobj=StringIO.StringIO(content)).read()

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

            codepage = codePageDict.get(lang, '')
            if codepage and control.setting('subtitles.utf') == '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:
            pass
Exemplo n.º 6
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()
Exemplo n.º 7
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
Exemplo n.º 8
0
    def sources(self, url, hostDict, hostprDict):
        sources = []

        try:
            if url is None:
                return sources

            data = urlparse.parse_qs(url)
            data = dict([(i, data[i][0]) if data[i] else (i, '')
                         for i in data])

            content_type = 'episode' if 'tvshowtitle' in data else 'movie'

            years = (data['year'], str(int(data['year']) + 1),
                     str(int(data['year']) - 1))

            if content_type == 'movie':
                title = cleantitle.get(data['title'])
                localtitle = cleantitle.get(data['localtitle'])
                ids = [data['imdb']]

                r = 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", "title", "originaltitle", "file"]}, "id": 1}'
                    % years)
                r = unicode(r, 'utf-8', errors='ignore')
                r = json.loads(r)['result']['movies']

                r = [
                    i for i in r if str(i['imdbnumber']) in ids or title in [
                        cleantitle.get(i['title'].encode('utf-8')),
                        cleantitle.get(i['originaltitle'].encode('utf-8'))
                    ]
                ]
                r = [
                    i for i in r
                    if not i['file'].encode('utf-8').endswith('.strm')
                ][0]

                r = control.jsonrpc(
                    '{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovieDetails", "params": {"properties": ["streamdetails", "file"], "movieid": %s }, "id": 1}'
                    % str(r['movieid']))
                r = unicode(r, 'utf-8', errors='ignore')
                r = json.loads(r)['result']['moviedetails']
            elif content_type == 'episode':
                title = cleantitle.get(data['tvshowtitle'])
                localtitle = cleantitle.get(data['localtvshowtitle'])
                season, episode = data['season'], data['episode']
                ids = [data['imdb'], data['tvdb']]

                r = control.jsonrpc(
                    '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"filter":{"or": [{"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}]}, "properties": ["imdbnumber", "title"]}, "id": 1}'
                    % years)
                r = unicode(r, 'utf-8', errors='ignore')
                r = json.loads(r)['result']['tvshows']

                r = [
                    i for i in r if str(i['imdbnumber']) in ids or title in [
                        cleantitle.get(i['title'].encode('utf-8')),
                        cleantitle.get(i['originaltitle'].encode('utf-8'))
                    ]
                ][0]

                r = control.jsonrpc(
                    '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "season", "operator": "is", "value": "%s"}, {"field": "episode", "operator": "is", "value": "%s"}]}, "properties": ["file"], "tvshowid": %s }, "id": 1}'
                    % (str(season), str(episode), str(r['tvshowid'])))
                r = unicode(r, 'utf-8', errors='ignore')
                r = json.loads(r)['result']['episodes']

                r = [
                    i for i in r
                    if not i['file'].encode('utf-8').endswith('.strm')
                ][0]

                r = control.jsonrpc(
                    '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodeDetails", "params": {"properties": ["streamdetails", "file"], "episodeid": %s }, "id": 1}'
                    % str(r['episodeid']))
                r = unicode(r, 'utf-8', errors='ignore')
                r = json.loads(r)['result']['episodedetails']

            url = r['file'].encode('utf-8')

            try:
                quality = int(r['streamdetails']['video'][0]['width'])
            except:
                quality = -1

            if quality >= 2160: quality = '4K'
            if quality >= 1440: quality = '1440p'
            if quality >= 1080: quality = '1080p'
            if 720 <= quality < 1080: quality = 'HD'
            if quality < 720: quality = 'SD'

            info = []
            try:
                f = control.openFile(url)
                s = f.size()
                f.close()
                s = '%.2f GB' % (float(s) / 1024 / 1024 / 1024)
                info.append(s)
            except:
                pass
            try:
                e = urlparse.urlparse(url).path.split('.')[-1].upper()
                info.append(e)
            except:
                pass
            info = ' | '.join(info)
            info = info.encode('utf-8')

            sources.append({
                'source': '0',
                'quality': quality,
                'language': 'en',
                'url': url,
                'info': info,
                'local': True,
                'direct': True,
                'debridonly': False
            })

            return sources
        except:
            return sources