Ejemplo n.º 1
0
def search(payload, method="general"):
    """ Main search entrypoint

    Args:
        payload (dict): Search payload from Quasar.
        method   (str): Type of search, can be ``general``, ``movie``, ``episode``, ``season`` or ``anime``

    Returns:
        list: All filtered results in the format Quasar expects
    """
    log.debug("Searching with payload (%s): %s" % (method, repr(payload)))

    if method == 'general':
        payload = {'title': payload}
        if 'query' in payload:
            payload['title'] = payload['query']

    global request_time
    global provider_names
    global provider_results
    global available_providers

    provider_names = []
    provider_results = []
    available_providers = 0
    request_time = time.time()

    providers = get_enabled_providers(method)

    if len(providers) == 0:
        notify(translation(32060), image=get_icon_path())
        log.error("No providers enabled")
        return []

    log.info(
        "Burstin' with %s" %
        ", ".join([definitions[provider]['name'] for provider in providers]))

    if get_setting('kodi_language', bool):
        kodi_language = xbmc.getLanguage(xbmc.ISO_639_1)
        if not kodi_language:
            log.warning("Kodi returned empty language code...")
        elif 'titles' not in payload or not payload['titles']:
            log.info("No translations available...")
        elif payload['titles'] and kodi_language not in payload['titles']:
            log.info("No '%s' translation available..." % kodi_language)

    p_dialog = xbmcgui.DialogProgressBG()
    p_dialog.create('Quasar [COLOR FFFF6B00]Burst[/COLOR]', translation(32061))
    for provider in providers:
        available_providers += 1
        provider_names.append(definitions[provider]['name'])
        task = Thread(target=run_provider, args=(provider, payload, method))
        task.start()

    providers_time = time.time()
    total = float(available_providers)

    # Exit if all providers have returned results or timeout reached, check every 100ms
    while time.time() - providers_time < timeout and available_providers > 0:
        timer = time.time() - providers_time
        log.debug("Timer: %ds / %ds" % (timer, timeout))
        if timer > timeout:
            break
        message = translation(
            32062
        ) % available_providers if available_providers > 1 else translation(
            32063)
        p_dialog.update(int((total - available_providers) / total * 100),
                        message=message)
        time.sleep(0.25)

    p_dialog.close()
    del p_dialog

    if available_providers > 0:
        message = u', '.join(provider_names)
        message = message + translation(32064)
        log.warning(message.encode('utf-8'))
        notify(message, ADDON_ICON)

    log.debug("all provider_results: %s" % repr(provider_results))

    filtered_results = apply_filters(provider_results)

    log.debug("all filtered_results: %s" % repr(filtered_results))

    log.info("Providers returned %d results in %s seconds" %
             (len(filtered_results), round(time.time() - request_time, 2)))

    return filtered_results
Ejemplo n.º 2
0
    def end(self):
        self.log('end')
        # Prevent the player from setting the sleep timer
        self.Player.stopped = True
        curtime = time.time()
        xbmc.executebuiltin("PlayerControl(RepeatOff)")
        self.isExiting = True
        updateDialog = xbmcgui.DialogProgressBG()
        updateDialog.create(ADDON_NAME, '')
        
        if self.isMaster and CHANNEL_SHARING == True:
            updateDialog.update(1, message='Exiting - Removing File Locks')
            GlobalFileLock.unlockFile('MasterLock')
        
        GlobalFileLock.close()

        if self.playerTimer.isAlive():
            self.playerTimer.cancel()
            self.playerTimer.join()

        if self.Player.isPlaying():
            self.lastPlayTime = self.Player.getTime()
            self.lastPlaylistPosition = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()
            self.Player.stop()

        updateDialog.update(2, message='Exiting - Stopping Threads')

        try:
            if self.channelLabelTimer.isAlive():
                self.channelLabelTimer.cancel()
                self.channelLabelTimer.join()
        except:
            pass

        updateDialog.update(3, message='Exiting - Stopping Threads')

        try:
            if self.notificationTimer.isAlive():
                self.notificationTimer.cancel()
                self.notificationTimer.join()
        except:
            pass

        updateDialog.update(4, message='Exiting - Stopping Threads')

        try:
            if self.infoTimer.isAlive():
                self.infoTimer.cancel()
                self.infoTimer.join()
        except:
            pass

        updateDialog.update(5, message='Exiting - Stopping Threads')

        try:
            if self.sleepTimeValue > 0:
                if self.sleepTimer.isAlive():
                    self.sleepTimer.cancel()
        except:
            pass

        updateDialog.update(6, message='Exiting - Stopping Threads')

        if self.channelThread.isAlive():
            for i in range(30):
                try:
                    self.channelThread.join(1.0)
                except:
                    pass

                if self.channelThread.isAlive() == False:
                    break

                updateDialog.update(6 + i, message='Exiting - Stopping Threads')

            if self.channelThread.isAlive():
                self.log("Problem joining channel thread", xbmc.LOGERROR)

        if self.isMaster:
            try:
                ADDON.setSetting('CurrentChannel', str(self.currentChannel))
            except:
                pass

            ADDON_SETTINGS.setSetting('LastExitTime', str(int(curtime)))

        if self.timeStarted > 0 and self.isMaster:
            updateDialog.update(35, message='Exiting - Saving Settings')
            validcount = 0

            for i in range(self.maxChannels):
                if self.channels[i].isValid:
                    validcount += 1
            
            if validcount > 0:
                incval = 65.0 / float(validcount)

                for i in range(self.maxChannels):
                    updateDialog.update(35 + int((incval * i)))

                    if self.channels[i].isValid:
                        if self.channels[i].mode & MODE_RESUME == 0:
                            ADDON_SETTINGS.setSetting('Channel_' + str(i + 1) + '_time', str(int(curtime - self.timeStarted + self.channels[i].totalTimePlayed)))
                        else:
                            if i == self.currentChannel - 1:
                                # Determine pltime...the time it at the current playlist position
                                pltime = 0
                                self.log("position for current playlist is " + str(self.lastPlaylistPosition))

                                for pos in range(self.lastPlaylistPosition):
                                    pltime += self.channels[i].getItemDuration(pos)

                                ADDON_SETTINGS.setSetting('Channel_' + str(i + 1) + '_time', str(pltime + self.lastPlayTime))
                            else:
                                tottime = 0

                                for j in range(self.channels[i].playlistPosition):
                                    tottime += self.channels[i].getItemDuration(j)

                                tottime += self.channels[i].showTimeOffset
                                ADDON_SETTINGS.setSetting('Channel_' + str(i + 1) + '_time', str(int(tottime)))
                                
                self.storeFiles()

        updateDialog.close()
        self.close()
Ejemplo n.º 3
0
    def make_xmltree(self):
        """
        Build the default viewtype expressions based on json file
        """
        xmltree = []
        expressions = {}
        viewtypes = {}

        p_dialog = xbmcgui.DialogProgressBG()
        p_dialog.create(ADDON.getLocalizedString(32002),
                        ADDON.getLocalizedString(32003))

        for v in self.meta.get('viewtypes', {}):
            expressions[v] = ''  # Construct our expressions dictionary
            viewtypes[v] = {}  # Construct our viewtypes dictionary

        # Build the definitions for each viewid
        p_dialog.update(25, message=ADDON.getLocalizedString(32006))
        for base_k, base_v in self.addon_meta.items():
            for contentid, viewid in base_v.items():
                if base_k == 'library':
                    viewtypes[viewid].setdefault(contentid, {}).setdefault(
                        'library', True)
                    continue
                if base_k == 'plugins':
                    viewtypes[viewid].setdefault(contentid, {}).setdefault(
                        'plugins', True)
                    continue
                for i in viewtypes:
                    listtype = 'whitelist' if i == viewid else 'blacklist'
                    viewtypes[i].setdefault(contentid,
                                            {}).setdefault(listtype, [])
                    viewtypes[i][contentid][listtype].append(base_k)

        # Build the visibility expression
        p_dialog.update(50, message=ADDON.getLocalizedString(32007))
        for viewid, base_v in viewtypes.items():
            for contentid, child_v in base_v.items():
                rule = self.meta.get('rules', {}).get(contentid, {}).get(
                    'rule')  # Container.Content()

                whitelist = ''
                if child_v.get('library'):
                    whitelist = 'String.IsEmpty(Container.PluginName)'
                for i in child_v.get('whitelist', []):
                    whitelist = utils.join_conditions(
                        whitelist,
                        'String.IsEqual(Container.PluginName,{})'.format(i))

                blacklist = ''
                if child_v.get('plugins'):
                    blacklist = '!String.IsEmpty(Container.PluginName)'
                    for i in child_v.get('blacklist', []):
                        blacklist = utils.join_conditions(
                            blacklist,
                            '!String.IsEqual(Container.PluginName,{})'.format(
                                i),
                            operator=' + ')

                affix = '[{}] | [{}]'.format(
                    whitelist, blacklist
                ) if whitelist and blacklist else whitelist or blacklist

                if affix:
                    expression = '[{} + [{}]]'.format(rule, affix)
                    expressions[viewid] = utils.join_conditions(
                        expressions.get(viewid), expression)

        # Build conditional rules for disabling view lock
        if self.meta.get('condition'):
            sep = ' | '
            for viewid in self.meta.get('viewtypes', {}):
                rule = [
                    '[{}]'.format(v.get('rule'))
                    for k, v in self.meta.get('rules', {}).items()
                    if viewid in v.get('viewtypes', [])
                ]
                rule_cond = '![{}] + [{}]'.format(self.meta.get('condition'),
                                                  sep.join(rule))
                rule_expr = '[{}] + [{}]'.format(self.meta.get('condition'),
                                                 expressions.get(viewid))
                expressions[viewid] = '[{}] | [{}]'.format(
                    rule_expr, rule_cond)

        # Build XMLTree
        p_dialog.update(75, message=ADDON.getLocalizedString(32008))
        for exp_name, exp_content in expressions.items():
            exp_include = 'True' if exp_content else 'False'
            exp_content = exp_content.replace(
                '[]', '[False]'
            ) if exp_content else 'False'  # Replace None conditions with explicit False because Kodi complains about empty visibility conditions
            exp_content = '[{}]'.format(exp_content)
            xmltree.append({
                'tag': 'expression',
                'attrib': {
                    'name': self.prefix + exp_name
                },
                'content': exp_content
            })
            xmltree.append({
                'tag': 'expression',
                'attrib': {
                    'name': self.prefix + exp_name + '_Include'
                },
                'content': exp_include
            })

        p_dialog.close()
        return xmltree
Ejemplo n.º 4
0
def UptomyAccount():
    addons = addon()

    if (addons.getSetting('hoster_uptobox_username')
            == '') and (addons.getSetting('hoster_uptobox_password') == ''):
        return
    oInputParameterHandler = cInputParameterHandler()
    sMediaUrl = oInputParameterHandler.getValue('sMediaUrl')

    oPremiumHandler = cPremiumHandler('uptobox')

    sHtmlContent = oPremiumHandler.GetHtml(URL_MAIN)
    cookies = GestionCookie().Readcookie('uptobox')

    aResult = re.search('<form id="fileupload" action="([^"]+)"', sHtmlContent,
                        re.DOTALL)
    if (aResult):
        upUrl = aResult.group(1).replace('upload?', 'remote?')

        if upUrl.startswith('//'):
            upUrl = 'https:' + upUrl

        fields = {'urls': '["' + sMediaUrl + '"]'}
        mpartdata = MPencode(fields)

        req = urllib2.Request(upUrl, mpartdata[1], headers)
        req.add_header('Content-Type', mpartdata[0].replace(',', ';'))
        req.add_header('Cookie', cookies)
        req.add_header('Content-Length', len(mpartdata[1]))

        # penible ce dialog auth
        xbmc.executebuiltin('Dialog.Close(all,true)')
        xbmcgui.Dialog().notification('Requête envoyée',
                                      'vous pouvez faire autre chose',
                                      xbmcgui.NOTIFICATION_INFO, 4000, False)

        try:
            rep = urllib2.urlopen(req)
        except UrlError:
            return ''

        sHtmlContent = rep.read()
        rep.close()

        sPattern = '{"id":.+?,(?:"size":|"progress":)([0-9]+)'
        oParser = cParser()
        aResult = oParser.parse(sHtmlContent, sPattern)
        if (aResult[0] == True):
            total = aResult[1][0]
            del aResult[1][0]

            dialog = xbmcgui.DialogProgressBG()
            dialog.create(SITE_NAME,
                          'Transfert de fichiers sur votre compte Uptobox')

            for aEntry in aResult[1]:
                dialog.update(
                    int(aEntry) * 100 / int(total), 'Upload en cours...')

                xbmc.sleep(500)
            dialog.close()

        else:
            # penible ce dialog auth
            xbmc.executebuiltin('Dialog.Close(all,true)')
            xbmcgui.Dialog().notification('Info upload', 'Fichier introuvable',
                                          xbmcgui.NOTIFICATION_INFO, 2000,
                                          False)
    else:
        # penible ce dialog auth
        xbmc.executebuiltin('Dialog.Close(all,true)')
        xbmcgui.Dialog().notification('Info upload', 'Erreur pattern',
                                      xbmcgui.NOTIFICATION_ERROR, 2000, False)
Ejemplo n.º 5
0
    def full_library_sync(self):
        """
        """
        kinds = [
            (v.PLEX_TYPE_MOVIE, v.PLEX_TYPE_MOVIE, itemtypes.Movie, False),
            (v.PLEX_TYPE_SHOW, v.PLEX_TYPE_SHOW, itemtypes.Show, False),
            (v.PLEX_TYPE_SEASON, v.PLEX_TYPE_SHOW, itemtypes.Season, False),
            (v.PLEX_TYPE_EPISODE, v.PLEX_TYPE_SHOW, itemtypes.Episode, False)
        ]
        if app.SYNC.enable_music:
            kinds.extend([
                (v.PLEX_TYPE_ARTIST, v.PLEX_TYPE_ARTIST, itemtypes.Artist,
                 False),
                (v.PLEX_TYPE_ALBUM, v.PLEX_TYPE_ARTIST, itemtypes.Album, True),
            ])
        # ADD NEW ITEMS
        # Already start setting up the iterators. We need to enforce
        # syncing e.g. show before season before episode
        iterator_queue = Queue.Queue()
        task = backgroundthread.FunctionAsTask(self.threaded_get_iterators,
                                               None, kinds, iterator_queue)
        backgroundthread.BGThreader.addTask(task)
        while True:
            self.section_success = True
            section = iterator_queue.get()
            iterator_queue.task_done()
            if section is None:
                break
            # Setup our variables
            self.plex_type = section.plex_type
            self.section_type = section.section_type
            self.context = section.context
            self.get_children = section.get_children
            # Now do the heavy lifting
            if self.isCanceled() or not self.addupdate_section(section):
                return False
            if self.section_success:
                # Need to check because a thread might have missed to get
                # some items from the PMS
                with PlexDB() as plexdb:
                    # Set the new time mark for the next delta sync
                    plexdb.update_section_last_sync(section.section_id,
                                                    self.current_sync)
        common.update_kodi_library(video=True, music=True)

        # Sync Plex playlists to Kodi and vice-versa
        if common.PLAYLIST_SYNC_ENABLED:
            if self.show_dialog:
                if self.dialog:
                    self.dialog.close()
                self.dialog = xbmcgui.DialogProgressBG()
                # "Synching playlists"
                self.dialog.create(utils.lang(39715))
            if not playlists.full_sync():
                return False

        # SYNC PLAYSTATE of ALL items (otherwise we won't pick up on items that
        # were set to unwatched). Also mark all items on the PMS to be able
        # to delete the ones still in Kodi
        LOG.info('Start synching playstate and userdata for every item')
        # In order to not delete all your songs again
        if app.SYNC.enable_music:
            kinds.extend([
                (v.PLEX_TYPE_SONG, v.PLEX_TYPE_ARTIST, itemtypes.Song, True),
            ])
        # Make sure we're not showing an item's title in the sync dialog
        self.title = ''
        self.threader.shutdown()
        self.threader = None
        if not self.show_dialog_userdata and self.dialog:
            # Close the progress indicator dialog
            self.dialog.close()
            self.dialog = None
        task = backgroundthread.FunctionAsTask(self.threaded_get_iterators,
                                               None,
                                               kinds,
                                               iterator_queue,
                                               all_items=True)
        backgroundthread.BGThreader.addTask(task)
        while True:
            section = iterator_queue.get()
            iterator_queue.task_done()
            if section is None:
                break
            # Setup our variables
            self.plex_type = section.plex_type
            self.section_type = section.section_type
            self.context = section.context
            self.get_children = section.get_children
            # Now do the heavy lifting
            if self.isCanceled() or not self.playstate_per_section(section):
                return False

        # Delete movies that are not on Plex anymore
        LOG.debug('Looking for items to delete')
        kinds = [(v.PLEX_TYPE_MOVIE, itemtypes.Movie),
                 (v.PLEX_TYPE_SHOW, itemtypes.Show),
                 (v.PLEX_TYPE_SEASON, itemtypes.Season),
                 (v.PLEX_TYPE_EPISODE, itemtypes.Episode)]
        if app.SYNC.enable_music:
            kinds.extend([(v.PLEX_TYPE_ARTIST, itemtypes.Artist),
                          (v.PLEX_TYPE_ALBUM, itemtypes.Album),
                          (v.PLEX_TYPE_SONG, itemtypes.Song)])
        for plex_type, context in kinds:
            # Delete movies that are not on Plex anymore
            while True:
                with context(self.current_sync) as ctx:
                    plex_ids = list(
                        ctx.plexdb.plex_id_by_last_sync(
                            plex_type, self.current_sync, BATCH_SIZE))
                    for plex_id in plex_ids:
                        if self.isCanceled():
                            return False
                        ctx.remove(plex_id, plex_type)
                if len(plex_ids) < BATCH_SIZE:
                    break
        LOG.debug('Done deleting')
        return True
Ejemplo n.º 6
0
    def __init__(self):

        self.log_list = []

        grab_all = True if __addon__.getSetting('all') == 'true' else False

        sets = {
            'kodi': {
                'function': self.grab_kodi_logs,
                'setting': False,
                'pointer': [('Kodi Log', 'HyhIT4UP'),
                            ('Kodi Old Log', '2qaAc90c')]
            },
            'config': {
                'function': self.grab_config,
                'setting': False,
                'pointer': [('Pi config', 'Ul2H1CLu')]
            },
            'packages': {
                'function': self.grab_osmc_packages,
                'setting': False,
                'pointer': [('OSMC Packages', '7nQvfy9a')]
            },
            'allothers': {
                'function': self.grab_all_other_packages,
                'setting': False,
                'pointer': [('All Other Packages', 'hwvkLCMX')]
            },
            'apt': {
                'function':
                self.grab_apt_logs,
                'setting':
                False,
                'pointer': [('APT term.log', 'RcBRrsRs'),
                            ('APT history.log', 'B8sj7DO8'),
                            ('APT sources.list', 'ZZz2wrJ1'),
                            ('APT apt.conf.d', 'fFsk1x85'),
                            ('APT preferences.d', 'vSKj25Lq')]
            },
            'fstab': {
                'function': self.grab_fstab,
                'setting': False,
                'pointer': [('fstab', 'qiE9Dtax')]
            },
            'advancedsettings': {
                'function': self.grab_advancedsettings,
                'setting': False,
                'pointer': [('advancedsettings.xml', 'C7hKmH1p')]
            },
            'sources': {
                'function': self.grab_sources,
                'setting': False,
                'pointer': [('sources.xml', 'SGkuGLGj')]
            },
            'keyboard': {
                'function': self.grab_keyboard,
                'setting': False,
                'pointer': [('keyboard.xml', 'MBom5YV6')]
            },
            'remote': {
                'function': self.grab_remote,
                'setting': False,
                'pointer': [('remote.xml', '5jmphjm3')]
            },
            'system': {
                'function': self.grab_system_logs,
                'setting': False,
                'pointer': [('System Journal', 'MyqVXi2x')]
            },
            'lirc': {
                'function': self.grab_lirc_conf,
                'setting': False,
                'pointer': [('lircd.conf', 'kdgLUcwP')]
            },
            'boot': {
                'function': self.grab_boot_contents,
                'setting': False,
                'pointer': [('/boot Contents', 'H3gEog10')]
            },
            'uname': {
                'function': self.grab_uname,
                'setting': False,
                'pointer': [('UNAME', '0wwkXuO5')]
            },
            'initd': {
                'function': self.grab_initd,
                'setting': False,
                'pointer': [('init.d', 'Vr58kq0w')]
            },
            'systemd': {
                'function': self.grab_systemd,
                'setting': False,
                'pointer': [('systemd', '86JFGfNO')]
            },
            'mem': {
                'function': self.grab_mem,
                'setting': False,
                'pointer': [('Memory', 'eWTP1Mc8')]
            },
            'diskspace': {
                'function': self.grab_diskspace,
                'setting': False,
                'pointer': [('Diskspace', 'qZy25Yas')]
            },
            'dmesg': {
                'function': self.grab_dmesg,
                'setting': False,
                'pointer': [('Kernel Message Log', 'Ad2zzd21')]
            },
        }

        keys = [
            'uname',
            'config',
            'advancedsettings',
            'keyboard',
            'remote',
            'sources',
            'fstab',
            'packages',
            'allothers',
            'apt',
            'system',
            'lirc',
            'initd',
            'systemd',
            'dmesg',
            'mem',
            'diskspace',
            'boot',
            'kodi',
        ]

        for key in keys:
            if grab_all and key not in []:
                sets[key]['setting'] = True
            else:
                sets[key]['setting'] = True if __addon__.getSetting(
                    key) == 'true' else False

        self.number_of_actions = sum(
            1 for key in keys if sets.get(key, {}).get('setting', False))

        log(self.number_of_actions)

        self.pDialog = xbmcgui.DialogProgressBG()
        self.pDialog.create(lang(32024), lang(32025))

        # add the quick look-up references
        for key in keys:
            if sets.get(key, {}).get('setting', False):
                pntr = sets.get(key, {}).get('pointer', [])
                for p in pntr:
                    # p is a tuple of the Label and lookup value
                    self.log_list.append(p[1] + '  :  ' + p[0] + '\n')
        self.log_list.append('\n')

        # add the logs themselves
        count = 0
        for key in keys:

            if sets.get(key, {}).get('setting', False):
                count += 1
                pct = int(100.0 * float(count) / float(self.number_of_actions))
                self.pDialog.update(percent=pct, message=lang(32036) % key)
                sets.get(key, {})['function']()

        self.tmp_log_location = '/var/tmp/uploadlog.txt'

        self.pDialog.update(percent=100, message=lang(32027))

        with open(self.tmp_log_location, 'w') as f:

            f.writelines(self.log_list)

        self.pDialog.update(percent=100, message=lang(32026))

        if USER_ACTION == 'copy':

            os.popen('sudo cp -rf %s /boot/' % self.tmp_log_location)

            ok = xbmcgui.Dialog().ok(lang(32013), lang(32040))

            self.pDialog.close()

        else:

            with os.popen(
                    'curl -X POST -s -T "%s" http://paste.osmc.io/documents' %
                    self.tmp_log_location) as f:

                line = f.readline()

                key = line.replace('{"key":"',
                                   '').replace('"}', '').replace('\n', '')

                log('pastio line: %s' % repr(line))

            self.pDialog.close()

            if not key:

                copy = xbmcgui.Dialog().yesno(lang(32013), lang(32023),
                                              lang(32039))

                if copy:

                    os.popen('sudo cp -rf %s /boot/' % self.tmp_log_location)

            else:

                self.url = 'http://paste.osmc.io/ %s' % key

                ok = xbmcgui.Dialog().ok(lang(32013), lang(32014) % self.url)
Ejemplo n.º 7
0
def GetPage(page_url, just_episodes=False):
    """   Generic Radio page scraper.   """

    pDialog = xbmcgui.DialogProgressBG()
    pDialog.create(translation(30319))

    html = OpenURL(page_url)

    total_pages = 1
    current_page = 1
    page_range = range(1)
    paginate = re.search(r'<ol.+?class="pagination.*?</ol>', html)
    next_page = 1
    if paginate:
        if int(ADDON.getSetting('radio_paginate_episodes')) == 0:
            current_page_match = re.search(r'page=(\d*)', page_url)
            if current_page_match:
                current_page = int(current_page_match.group(1))
            page_range = range(current_page, current_page + 1)
            next_page_match = re.search(
                r'<li class="pagination__next"><a href="(.*?page=)(.*?)">',
                paginate.group(0))
            if next_page_match:
                page_base_url = next_page_match.group(1)
                next_page = int(next_page_match.group(2))
            else:
                next_page = current_page
            page_range = range(current_page, current_page + 1)
        else:
            pages = re.findall(r'<li.+?class="pagination__page.*?</li>',
                               paginate.group(0))
            if pages:
                last = pages[-1]
                last_page = re.search(r'<a.+?href="(.*?=)(.*?)"', last)
                page_base_url = last_page.group(1)
                total_pages = int(last_page.group(2))
            page_range = range(1, total_pages + 1)

    for page in page_range:

        if page > current_page:
            page_url = 'http://www.bbc.co.uk' + page_base_url + str(page)
            html = OpenURL(page_url)

        masthead_title = ''
        masthead_title_match = re.search(
            r'<div.+?id="programmes-main-content".*?<span property="name">(.+?)</span>',
            html)
        if masthead_title_match:
            masthead_title = masthead_title_match.group(1)

        list_item_num = 1

        programmes = html.split('<div class="programme ')
        for programme in programmes:

            if not programme.startswith("programme--radio"):
                continue

            if "available" not in programme:  #TODO find a more robust test
                continue

            series_id = ''
            series_id_match = re.search(
                r'<a class="iplayer-text js-lazylink__link" href="/programmes/(.+?)/episodes/player"',
                programme)
            if series_id_match:
                series_id = series_id_match.group(1)

            programme_id = ''
            programme_id_match = re.search(r'data-pid="(.+?)"', programme)
            if programme_id_match:
                programme_id = programme_id_match.group(1)

            name = ''
            name_match = re.search(r'<span property="name">(.+?)</span>',
                                   programme)
            if name_match:
                name = name_match.group(1)

            subtitle = ''
            subtitle_match = re.search(
                r'<span class="programme__subtitle.+?property="name">(.*?)</span>(.*?property="name">(.*?)</span>)?',
                programme)
            if subtitle_match:
                series = subtitle_match.group(1)
                episode = subtitle_match.group(3)
                if episode:
                    subtitle = "(%s, %s)" % (series, episode)
                else:
                    if series.strip():
                        subtitle = "(%s)" % series

            image = ''
            image_match = re.search(
                r'<meta property="image" content="(.+?)" />', programme)
            if image_match:
                image = image_match.group(1)

            synopsis = ''
            synopsis_match = re.search(
                r'<span property="description">(.+?)</span>', programme)
            if synopsis_match:
                synopsis = synopsis_match.group(1)

            station = ''
            station_match = re.search(
                r'<p class="programme__service.+?<strong>(.+?)</strong>.*?</p>',
                programme)
            if station_match:
                station = station_match.group(1).strip()

            series_title = "[B]%s - %s[/B]" % (station, name)
            if just_episodes:
                title = "[B]%s[/B] - %s" % (masthead_title, name)
            else:
                title = "[B]%s[/B] - %s %s" % (station, name, subtitle)

            if series_id:
                AddMenuEntry(series_title, series_id, 131, image, synopsis, '')
            elif programme_id:  #TODO maybe they are not always mutually exclusive

                url = "http://www.bbc.co.uk/programmes/%s" % programme_id
                CheckAutoplay(title, url, image, ' ', '')

            percent = int(100 * (page + list_item_num / len(programmes)) /
                          total_pages)
            pDialog.update(percent, translation(30319), name)

            list_item_num += 1

        percent = int(100 * page / total_pages)
        pDialog.update(percent, translation(30319))

    if int(ADDON.getSetting('radio_paginate_episodes')) == 0:
        if current_page < next_page:
            page_url = 'http://www.bbc.co.uk' + page_base_url + str(next_page)
            AddMenuEntry(" [COLOR ffffa500]%s >>[/COLOR]" % translation(30320),
                         page_url, 136, '', '', '')

    #BUG: this should sort by original order but it doesn't (see http://trac.kodi.tv/ticket/10252)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)
    xbmcplugin.addSortMethod(int(sys.argv[1]),
                             xbmcplugin.SORT_METHOD_VIDEO_TITLE)

    pDialog.close()
Ejemplo n.º 8
0
def dialog_progress_bg(heading, message=""):
    dialog = xbmcgui.DialogProgressBG()
    dialog.create(heading, message)
    return dialog
Ejemplo n.º 9
0
    def setup(self, standings):
        progress = xbmcgui.DialogProgressBG()
        progress.create("This might take a minute")
        percentage = 0

        rows_needed = 0
        cols_needed = 12
        h = standings.pop('Headers')
        lname = standings.pop('League Name')
        if 'Groups' in standings.keys()[0]:
            #Need 2x the columns
            cols_needed = 24
            #Need 5 * number of groups in a column for rows (4 teams + headers per group)
            rows_needed = 5 * len(standings[standings.keys()[0]])
        else:
            for x, y in standings.iteritems():
                rows_needed += len(y)
            rows_needed += 3
        self.setGeometry(1280, 720, rows_needed, cols_needed)

        if len(standings.keys()) == 1:
            league_name = standings.keys()[0]
            league_standings = standings[league_name]
            l = pyxbmct.Label('[B]%s[/B]' % league_name,
                              alignment=pyxbmct.ALIGN_CENTER)
            self.placeControl(l, 0, 1, columnspan=3)
            for i, header in enumerate(h):
                tmp3 = pyxbmct.Label('[B]%s[/B]' % header,
                                     alignment=pyxbmct.ALIGN_CENTER)
                self.placeControl(tmp3, 0, 4 + i)
            for number, team_dict in league_standings.iteritems():
                position = pyxbmct.Label(str(number),
                                         alignment=pyxbmct.ALIGN_CENTER)
                self.placeControl(position, int(number), 0)
                tname = pyxbmct.Label(team_dict['Name'],
                                      alignment=pyxbmct.ALIGN_CENTER)
                self.placeControl(tname, int(number), 1, columnspan=3)
                for index, head in enumerate(h):
                    tmp2 = pyxbmct.Label(team_dict[head],
                                         alignment=pyxbmct.ALIGN_CENTER)
                    self.placeControl(tmp2, int(number), 4 + index)
        elif 'Conference' in standings.keys()[0]:
            #Major League Soccer
            sub_title1 = standings.keys()[0]
            sub_teams1 = len(standings[sub_title1])
            league_standings1 = standings[sub_title1]
            sub_title2 = standings.keys()[1]
            sub_teams2 = len(standings[sub_title2])
            league_standings2 = standings[sub_title2]
            #Add East Division
            stitle1 = pyxbmct.Label('[B]%s[/B]' % sub_title1,
                                    alignment=pyxbmct.ALIGN_CENTER)
            self.placeControl(stitle1, 0, 1, columnspan=3)
            for i, header in enumerate(h):
                tmp3 = pyxbmct.Label('[B]%s[/B]' % header,
                                     alignment=pyxbmct.ALIGN_CENTER)
                self.placeControl(tmp3, 0, 4 + i)
            for number, team_dict in league_standings1.iteritems():
                #Add row
                position = pyxbmct.Label(str(number),
                                         alignment=pyxbmct.ALIGN_CENTER)
                self.placeControl(position, int(number), 0)
                tname = pyxbmct.Label(team_dict['Name'],
                                      alignment=pyxbmct.ALIGN_CENTER)
                self.placeControl(tname, int(number), 1, columnspan=3)
                for index, header in enumerate(h):
                    #Add each stat (column) for the row
                    tmp2 = pyxbmct.Label(team_dict[header],
                                         alignment=pyxbmct.ALIGN_CENTER)
                    self.placeControl(tmp2, int(number), 4 + index)
            #Add West Division
            stitle2 = pyxbmct.Label('[B]%s[/B]' % sub_title2,
                                    alignment=pyxbmct.ALIGN_CENTER)
            self.placeControl(stitle2, sub_teams1 + 2, 1, columnspan=3)
            for i, header in enumerate(h):
                tmp3 = pyxbmct.Label('[B]%s[/B]' % header,
                                     alignment=pyxbmct.ALIGN_CENTER)
                self.placeControl(tmp3, sub_teams1 + 2, 4 + i)
            for p, pos in league_standings2.iteritems():
                #Add row
                position = pyxbmct.Label(str(p),
                                         alignment=pyxbmct.ALIGN_CENTER)
                self.placeControl(position, sub_teams1 + 2 + int(p), 0)
                tname = pyxbmct.Label(pos['Name'],
                                      alignment=pyxbmct.ALIGN_CENTER)
                self.placeControl(tname,
                                  sub_teams1 + 2 + int(p),
                                  1,
                                  columnspan=3)
                for num, head in enumerate(h):
                    #Add each stat (column) for the row
                    tmp2 = pyxbmct.Label(pos[head],
                                         alignment=pyxbmct.ALIGN_CENTER)
                    self.placeControl(tmp2, sub_teams1 + 2 + int(p), 4 + num)
        else:
            #Europa & Champions Leagues
            #Place headers in both columns
            for i, header in enumerate(h):
                tmp1 = pyxbmct.Label('[B]%s[/B]' % header,
                                     alignment=pyxbmct.ALIGN_CENTER)
                self.placeControl(tmp1, 0, 4 + i)
                tmp2 = pyxbmct.Label('[B]%s[/B]' % header,
                                     alignment=pyxbmct.ALIGN_CENTER)
                self.placeControl(tmp2, 0, 16 + i)
            ncol = 0
            for grouping_name, groups in sorted(standings.iteritems()):
                nrow = 0
                for group, teams in sorted(groups.iteritems()):
                    gname = pyxbmct.Label('[B]%s[/B]' % group,
                                          alignment=pyxbmct.ALIGN_CENTER)
                    self.placeControl(gname, nrow, ncol, columnspan=4)
                    for i, header in enumerate(h):
                        tmp1 = pyxbmct.Label('[B]%s[/B]' % header,
                                             alignment=pyxbmct.ALIGN_CENTER)
                        self.placeControl(tmp1, nrow, 4 + i)
                        tmp2 = pyxbmct.Label('[B]%s[/B]' % header,
                                             alignment=pyxbmct.ALIGN_CENTER)
                        self.placeControl(tmp2, nrow, 16 + i)
                    nrow += 1
                    for position, team_data in teams.iteritems():
                        position_in_group = pyxbmct.Label(
                            '[B]%s[/B]' % str(position),
                            alignment=pyxbmct.ALIGN_CENTER)
                        self.placeControl(position_in_group, nrow, ncol)
                        tname = pyxbmct.Label(team_data['Name'],
                                              alignment=pyxbmct.ALIGN_CENTER)
                        self.placeControl(tname, nrow, ncol + 1, columnspan=3)
                        for i, header in enumerate(h):
                            tstat = pyxbmct.Label(
                                team_data[header],
                                alignment=pyxbmct.ALIGN_CENTER)
                            self.placeControl(tstat, nrow, ncol + 4 + i)
                        nrow += 1
                ncol = 12
                percentage += 50
                progress.update(percentage, ' It\'ll be worth it, I promise!')
        progress.close()
Ejemplo n.º 10
0
def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
    allocate = True

    try:
        log("XXX KODI XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
            )
        log("OS platform: %s %s" % (platform.system(), platform.release()))
        log("xbmc/kodi version: %s" % xbmc.getInfoLabel("System.BuildVersion"))
        xbmc_version = int(xbmc.getInfoLabel("System.BuildVersion")[:2])
        log("Architecture: %s %s" % (str(platform.machine()), \
                        str(sys.maxsize > 2 ** 32 and "64-bit" or "32-bit")))
        log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX KODI & platform XXXX"
            )
    except:
        log(traceback.format_exc())

    # -- adfly: ------------------------------------
    if url.startswith("http://adf.ly/"):
        try:
            data = httptools.downloadpage(url).data
            url = decode_adfly(data)
        except:
            ddd = xbmcgui.Dialog()
            ddd.ok(
                msg_header + ": Sin soporte adf.ly",
                "El script no tiene soporte para el acortador de urls adf.ly.",
                "", "url: " + url)
            return
    """
    # -- Necesario para algunas webs ----------------------------
    if not url.endswith(".torrent") and not url.startswith("magnet"):
        #t_file = httptools.downloadpage(url, follow_redirects=False).headers["location"]
        t_file = scrapertools.get_header_from_response(url, header_to_get="location")
        if t_file:
            if len(t_file) > 0:
                url = t_file
                t_file = httptools.downloadpage(url, follow_redirects=False).headers["location"]
            if len(t_file) > 0:
                url = t_file
    """

    # -- Crear dos carpetas en descargas para los archivos ------
    save_path_videos = os.path.join(DOWNLOAD_PATH, "MCT-torrent-videos")
    save_path_torrents = os.path.join(DOWNLOAD_PATH, "MCT-torrents")
    if not os.path.exists(save_path_torrents): os.mkdir(save_path_torrents)
    video_path = ''
    global bkg_user
    bkg_user = False
    DOWNGROUND = False
    if item.downloadFilename:  # Descargas
        BACKGROUND = True
        DOWNGROUND = True
        bkg_user = True
    ses_lt = False
    if item:
        if item.contentType == 'movie':
            video_path = '%s-%s' % (item.contentTitle,
                                    item.infoLabels['tmdb_id'])
        else:
            video_path = '%s-%sx%s-%s' % (item.contentSerieName, item.contentSeason, \
                            item.contentEpisodeNumber, item.infoLabels['tmdb_id'])
        item.rar_path = video_path

    # -- Usar - archivo torrent desde web, magnet o HD ---------
    if not os.path.isfile(url) and not url.startswith("magnet"):
        # -- http - crear archivo torrent -----------------------
        data = url_get(url)

        # -- El nombre del torrent será el que contiene en los --
        # -- datos.                                             -
        re_name = urllib.parse.unquote(
            scrapertools.find_single_match(data, ':name\d+:(.*?)\d+:'))
        torrent_file = os.path.join(save_path_torrents,
                                    encode(re_name + '.torrent'))

        f = open(torrent_file, 'wb')
        f.write(data)
        f.close()
    elif os.path.isfile(url):
        # -- file - para usar torrens desde el HD ---------------
        torrent_file = url
    else:
        # -- magnet ---------------------------------------------
        torrent_file = url
    # -----------------------------------------------------------

    # -- MCT - MiniClienteTorrent -------------------------------
    try:
        log("XXX libtorrent pathname: %s" % str(LIBTORRENT_PATH))
        ses = lt.session()
    except Exception as e:
        do = xbmcgui.Dialog()
        e = e1 or e2
        do.ok('ERROR en el cliente MCT Libtorrent',
              'Módulo no encontrado o imcompatible con el dispositivo.',
              'Reporte el fallo adjuntando un "log".', str(e))
        return

    log("XXX libtorrent version: %s" % lt.version)
    log("##### Torrent file: %s ##" % torrent_file)

    ses.add_dht_router("router.bittorrent.com", 6881)
    ses.add_dht_router("router.utorrent.com", 6881)
    ses.add_dht_router("dht.transmissionbt.com", 6881)

    trackers = [
        "udp://tracker.openbittorrent.com:80/announce",
        "http://tracker.torrentbay.to:6969/announce",
        "http://tracker.pow7.com/announce",
        "udp://tracker.ccc.de:80/announce",
        "udp://open.demonii.com:1337",
        "http://9.rarbg.com:2710/announce",
        "http://bt.careland.com.cn:6969/announce",
        "http://explodie.org:6969/announce",
        "http://mgtracker.org:2710/announce",
        "http://tracker.best-torrents.net:6969/announce",
        "http://tracker.tfile.me/announce",
        "http://tracker1.wasabii.com.tw:6969/announce",
        "udp://9.rarbg.com:2710/announce",
        "udp://9.rarbg.me:2710/announce",
        "udp://coppersurfer.tk:6969/announce",
        "http://www.spanishtracker.com:2710/announce",
        "http://www.todotorrents.com:2710/announce",
    ]

    video_file = ""
    # -- magnet2torrent -----------------------------------------
    if torrent_file.startswith("magnet"):
        try:
            import zlib
            btih = hex(
                zlib.crc32(
                    scrapertools.find_single_match(
                        torrent_file,
                        'magnet:\?xt=urn:(?:[A-z0-9:]+|)([A-z0-9]{32})'))
                & 0xffffffff)
            files = [
                f for f in os.listdir(save_path_torrents)
                if os.path.isfile(os.path.join(save_path_torrents, f))
            ]
            for file in files:
                if btih in os.path.basename(file):
                    torrent_file = os.path.join(save_path_torrents, file)
        except:
            pass

    if torrent_file.startswith("magnet"):
        try:
            tempdir = tempfile.mkdtemp()
        except IOError:
            tempdir = os.path.join(save_path_torrents, "temp")
            if not os.path.exists(tempdir):
                os.mkdir(tempdir)
        params = {
            'save_path': tempdir,
            'trackers': trackers,
            'storage_mode': lt.storage_mode_t.storage_mode_allocate
        }
        """
        ,
            'paused': False,
            'auto_managed': True,
            'duplicate_is_error': True
        """
        h = lt.add_magnet_uri(ses, torrent_file, params)
        dp = xbmcgui.DialogProgress()
        dp.create(msg_header)
        while not h.has_metadata():
            message, porcent, msg_file, s, download = getProgress(
                h, "Creando torrent desde magnet")
            dp.update(porcent, message, msg_file)
            if s.state == 1: download = 1
            if dp.iscanceled():
                dp.close()
                remove_files(download, torrent_file, video_file, ses, h)
                return
            h.force_dht_announce()
            xbmc.sleep(1000)

        dp.close()
        info = h.get_torrent_info()
        data = lt.bencode(lt.create_torrent(info).generate())

        #torrent_file = os.path.join(save_path_torrents, unicode(info.name()+"-"+btih, "'utf-8'", errors="replace") + ".torrent")
        torrent_file = os.path.join(save_path_torrents,
                                    info.name() + "-" + btih + ".torrent")
        f = open(torrent_file, 'wb')
        f.write(data)
        f.close()
        ses.remove_torrent(h)
        filetools.rmdirtree(tempdir)
    # -----------------------------------------------------------

    # -- Archivos torrent ---------------------------------------
    e = lt.bdecode(open(torrent_file, 'rb').read())
    info = lt.torrent_info(e)

    # -- El más gordo o uno de los más gordo se entiende que es -
    # -- el vídeo o es el vídeo que se usará como referencia    -
    # -- para el tipo de archivo                                -
    log("##### Archivos ## %s ##" % len(info.files()))
    _index_file, _video_file, _size_file = get_video_file(info)

    # -- Prioritarizar/Seleccionar archivo-----------------------
    _index, video_file, video_size, len_files = get_video_files_sizes(info)
    if len_files == 0:
        dp = xbmcgui.Dialog().ok(
            "No se puede reproducir",
            "El torrent no contiene ningún archivo de vídeo")

    if _index < 0:
        log("##### parts = %s #########" % str(video_file))
        log("##### video_size = %s #########" % str(video_size))
        log("##### _index = %s #########" % str(_index))
        #if _index == -1:
        #    _index = _index_file
        #    video_size = _size_file
        video_file = _video_file
    else:
        log("##### video_size = %s #########" % str(video_size))
        log("##### _index = %s #########" % str(_index))
    _video_file_ext = os.path.splitext(_video_file)[1]
    log("##### _video_file ## %s ##" % str(_video_file))
    log("##### _video_file_ext ## %s ##" % _video_file_ext)

    dp_cerrado = True
    rar = False
    global extracted_rar
    extracted_rar = False
    global erase_file_path
    erase_file_path = ''

    if _video_file_ext == ".rar":
        rar = True
        filename = video_file
        if "/" in filename:
            filename = filename.split("/")[1]
        if (RAR and BACKGROUND):
            xbmcgui.Dialog().notification("Encontrado archivo .RAR de %.2f MB" % (video_size / 1048576.0),
                                        "Puedes realizar otras tareas en Kodi mientrastanto. " + \
                                        "Te informaremos...", time=10000)
            dialog = True
        else:
            dialog = xbmcgui.Dialog().yesno(
                "Encontrado archivo .RAR...", "Nombre: %s" % filename,
                "Tamaño: %.2f MB" % (video_size / 1048576.0),
                "¿Descargar en segundo plano? Cancelar en menú Descargas")
        if dialog:
            dp_cerrado = False
            dp = xbmcgui.DialogProgressBG()
            dp.create(msg_header)

    if (_video_file_ext == ".avi" or _video_file_ext == ".mp4"
            or _video_file_ext == ".mkv") and allocate:
        log("##### storage_mode_t.storage_mode_allocate (" + _video_file_ext +
            ") #####")
        h = ses.add_torrent({
            'ti':
            info,
            'save_path':
            save_path_videos,
            'trackers':
            trackers,
            'storage_mode':
            lt.storage_mode_t.storage_mode_allocate
        })
    else:
        log("##### storage_mode_t.storage_mode_sparse (" + _video_file_ext +
            ") #####")
        h = ses.add_torrent({
            'ti':
            info,
            'save_path':
            save_path_videos,
            'trackers':
            trackers,
            'storage_mode':
            lt.storage_mode_t.storage_mode_sparse
        })
        allocate = True
    global ses_lt
    ses_lt = True
    # -----------------------------------------------------------

    # -- Descarga secuencial - trozo 1, trozo 2, ... ------------
    h.set_sequential_download(True)

    h.force_reannounce()
    h.force_dht_announce()
    h.set_upload_limit(UPLOAD_LIMIT)

    # -- Inicio de variables para 'pause' automático cuando el  -
    # -- el vídeo se acerca a una pieza sin completar           -
    is_greater_num_pieces = False
    is_greater_num_pieces_plus = False
    is_greater_num_pieces_pause = False

    porcent4first_pieces = int(video_size * 0.000000005)
    porcent4first_pieces = BUFFER
    if porcent4first_pieces < BUFFER: porcent4first_pieces = BUFFER
    if porcent4first_pieces > 100: porcent4first_pieces = 100
    porcent4last_pieces = int(old_div(porcent4first_pieces, 2))

    num_pieces_to_resume = int(video_size * 0.0000000025)
    if num_pieces_to_resume < 10: num_pieces_to_resume = 10
    if num_pieces_to_resume > 25: num_pieces_to_resume = 25

    log("##### porcent4first_pieces ## %s ##" % porcent4first_pieces)
    log("##### porcent4last_pieces ## %s ##" % porcent4last_pieces)
    log("##### num_pieces_to_resume ## %s ##" % num_pieces_to_resume)

    # -- Prioritarizar o seleccionar las piezas del archivo que -
    # -- se desea reproducir con 'file_priorities'              -
    piece_set = set_priority_pieces(h, _index, video_file, video_size,
                                    porcent4first_pieces, porcent4last_pieces,
                                    allocate)
    global tot_piece_set
    tot_piece_set = len(piece_set)
    log("##### total piece_set ## %s ##" % len(piece_set))

    if dp_cerrado:
        if bkg_user:
            dp = xbmcgui.DialogProgressBG()
            dp.create(msg_header)
        else:
            # -- Crear diálogo de progreso para el primer bucle ---------
            dp = xbmcgui.DialogProgress()
            dp.create(msg_header)

    _pieces_info = {}

    ren_video_file = os.path.join(save_path_videos, video_file)
    # -- Doble bucle anidado ------------------------------------
    # -- Descarga - Primer bucle
    while not h.is_seed():
        s = h.status()

        xbmc.sleep(1000)
        if not dp_cerrado and not BACKGROUND:
            dp.close()
            dp_cerrado = True
            dp = xbmcgui.DialogProgress()
            dp.create(msg_header)

        # -- Recuperar los datos del progreso -------------------
        message, porcent, msg_file, s, download = getProgress(h,
                                                              video_file,
                                                              _pf=_pieces_info)

        # -- Si hace 'checking' existe descarga -----------------
        # -- 'download' Se usará para saber si hay datos        -
        # -- descargados para el diálogo de 'remove_files'      -
        if s.state == 1: download = 1

        if (s.state == 5 or s.state == 4) and rar:
            # -- Borrar sesión para que libere los archivos y se pueda renombrar la carpeta -------
            ses.pause()
            #video_file, rar, play_file = extract_files(video_file, save_path_videos, password, dp, item=item)
            video_file, rar, play_file, erase_path = torr.extract_files(video_file, \
                            save_path_videos, password, dp, item=item, torr_client='MCT')   # ... extraemos el vídeo del RAR
            dp.close()

            erase_file_path = erase_path
            ren_video_file = erase_file_path
            extracted_rar = rar
            if not play_file:
                remove_files(download, torrent_file, erase_file_path, ses, h,
                             ren_video_file)
                return
            is_view = "Ok"
            save_path_videos = play_file
            xbmc.sleep(3000)

        # -- Player - play --------------------------------------
        # -- Comprobar si se han completado las piezas para el  -
        # -- inicio del vídeo                                   -
        first_pieces = True
        #if not extracted_rar:
        _c = 0
        for i in range(piece_set[0], piece_set[porcent4first_pieces]):
            first_pieces &= h.have_piece(i)
            if h.have_piece(i): _c += 1
        _pieces_info = {'current': 0, 'continuous': "%s/%s" % (_c, porcent4first_pieces), \
                        'continuous2': "", 'have': h.status().num_pieces, 'len': len(piece_set)}

        last_pieces = True
        if not allocate:
            _c = len(piece_set) - 1
            _cc = 0
            for i in range(
                    len(piece_set) - porcent4last_pieces, len(piece_set)):
                last_pieces &= h.have_piece(i)
                if h.have_piece(i):
                    _c -= 1
                    _cc += 1
            _pieces_info['continuous2'] = "[%s/%s] " % (_cc,
                                                        porcent4last_pieces)

        if is_view != "Ok" and h.status().num_pieces >= BUFFER and not rar and not bkg_user \
                            or ((s.state == 5 or s.state == 4) and bkg_user):
            _pieces_info['continuous2'] = ""
            log("##### porcent [%.2f%%]" % (s.progress * 100))
            dp.close()
            dp_cerrado = True
            if not bkg_user:
                is_view = "Ok"
            else:
                remove_files(download, torrent_file, video_file, ses, h,
                             ren_video_file)
                return

        if is_view == "Ok":
            # -- Esperando a que termine otra reproducción --------------------------
            while xbmc.Player().isPlaying():
                xbmc.sleep(3000)

            # -- Player - Ver el vídeo --------------------------
            playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            playlist.clear()

            ren_video_file = os.path.join(save_path_videos, video_file)
            try:
                playlist.add(ren_video_file, xlistitem)
            except:
                playlist.add(ren_video_file)

            if xbmc_version < 17:
                player = play_video(xbmc.PLAYER_CORE_AUTO)
            else:
                player = play_video()
            player.play(playlist)

            # -- Contador de cancelaciones para la ventana de   -
            # -- 'pause' automático                             -
            is_greater_num_pieces_canceled = 0
            continuous_pieces = 0
            porcent_time = 0.00
            current_piece = 0
            set_next_continuous_pieces = porcent4first_pieces

            # -- Impedir que kodi haga 'resume' a un archivo ----
            # -- que se reprodujo con anterioridad y que se     -
            # -- eliminó para impedir que intente la reprucción -
            # -- en una pieza que aún no se ha completado y se  -
            # -- active 'pause' automático                      -
            not_resume = True

            # -- Bandera subTítulos
            _sub = False

            # -- Segundo bucle - Player - Control de eventos ----
            bkg_auto = True
            log("##### PLAY %s" % (h.status().num_pieces))
            if item: torr.mark_auto_as_watched(item)
            if ses_lt: h.set_download_limit(DOWNLOAD_LIMIT)
            while player.isPlaying():

                # -- Impedir que kodi haga 'resume' al inicio ---
                # -- de la descarga de un archivo conocido      -
                if not_resume:
                    player.seekTime(0)
                    not_resume = False

                # -- Control 'pause' automático                 -
                continuous_pieces = count_completed_continuous_pieces(
                    h, piece_set)

                if xbmc.Player().isPlaying() and not rar:

                    # -- Porcentage del progreso del vídeo ------
                    # -- En kodi 18.x se debe controlar         -
                    # -- ZeroDivisionError: float division by   -
                    # -- zero                                   -
                    player_getTime = player.getTime()
                    player_getTotalTime = player.getTotalTime()
                    try:
                        porcent_time = old_div(player_getTime,
                                               player_getTotalTime) * 100
                    except:
                        porcent_time = 0

                    # -- Pieza que se está reproduciendo --------
                    # -- En kodi 18.x se debe controlar         -
                    # -- ZeroDivisionError: float division by   -
                    # -- zero                                   -
                    try:
                        current_piece = int(
                            old_div(porcent_time, 100) * len(piece_set))
                    except:
                        current_piece = 0

                    # -- Banderas de control --------------------
                    is_greater_num_pieces = (
                        current_piece >
                        continuous_pieces - num_pieces_to_resume)
                    #is_greater_num_pieces_plus = (current_piece + porcent4first_pieces > continuous_pieces)
                    is_greater_num_pieces_plus = (current_piece + BUFFER >
                                                  continuous_pieces)
                    #is_greater_num_pieces_finished = (current_piece + porcent4first_pieces >= len(piece_set))
                    is_greater_num_pieces_finished = (current_piece + BUFFER >=
                                                      len(piece_set))

                    # -- Activa 'pause' automático --------------
                    if is_greater_num_pieces and not player.paused and not is_greater_num_pieces_finished:
                        is_greater_num_pieces_pause = True
                        player.pause()

                    if continuous_pieces >= set_next_continuous_pieces:
                        set_next_continuous_pieces = continuous_pieces + num_pieces_to_resume
                    next_continuous_pieces = str(
                        continuous_pieces -
                        current_piece) + "/" + str(set_next_continuous_pieces -
                                                   current_piece)
                    _pieces_info = {
                        'current': current_piece,
                        'continuous': next_continuous_pieces,
                        'continuous2': _pieces_info['continuous2'],
                        'have': h.status().num_pieces,
                        'len': len(piece_set)
                    }

                # -- Cerrar el diálogo de progreso --------------
                if player.resumed:
                    dp.close()

                # -- Mostrar el diálogo de progreso -------------
                if player.paused and dp_cerrado and not rar:
                    # -- Crear diálogo si no existe -------------
                    log("##### PAUSED %s" % (h.status().num_pieces))
                    if not player.statusDialogoProgress:
                        dp = xbmcgui.DialogProgressBG()
                        dp.create(msg_header)
                        player.setDialogoProgress()

                    # -- Diálogos de estado en el visionado -----
                    if not h.is_seed():
                        # -- Recuperar los datos del progreso ---
                        message, porcent, msg_file, s, download = getProgress(
                            h, video_file, _pf=_pieces_info)
                        dp.update(porcent, message,
                                  '[CR]' + message + '[CR]' + msg_file)
                    else:
                        dp.update(100, "Descarga completa: " + video_file)

                    # -- Se canceló el progreso en el visionado -
                    # -- Continuar                              -
                    if not bkg_auto and dp.iscanceled():
                        dp.close()
                        player.pause()

                    # -- Se canceló el progreso en el visionado -
                    # -- en la ventana de 'pause' automático.   -
                    # -- Parar si el contador llega a 3         -
                    if not bkg_auto and dp.iscanceled(
                    ) and is_greater_num_pieces_pause:
                        is_greater_num_pieces_canceled += 1
                        if is_greater_num_pieces_canceled == 3:
                            player.stop()

                    # -- Desactiva 'pause' automático y ---------
                    # -- reinicia el contador de cancelaciones  -
                    if not is_greater_num_pieces_plus and is_greater_num_pieces_pause:
                        dp.close()
                        player.pause()
                        is_greater_num_pieces_pause = False
                        is_greater_num_pieces_canceled = 0

                    # -- El usuario cancelo el visionado --------
                    # -- Terminar                               -
                    if player.ended:
                        # -- Diálogo eliminar archivos ----------
                        remove_files(download, torrent_file, video_file, ses,
                                     h, ren_video_file)
                        return

                xbmc.sleep(1000)

        # -- Kodi - Se cerró el visionado -----------------------
        # -- Continuar | Terminar                               -
        if is_view == "Ok" and not xbmc.Player().isPlaying():
            dp.close()

            if h.status().num_pieces < tot_piece_set:
                # -- Diálogo continuar o terminar ---------------
                # Preguntamos si el usuario quiere pasar a backgroung
                ok = xbmcgui.Dialog().yesno(
                    msg_header,
                    "¿Borramos los archivo descargados? (incompletos)",
                    "Selecciona NO para seguir descargando en segundo plano")
            else:
                ok = True
            # -- NO ---------------------------------------------
            if not ok:
                is_view = None
                bkg_user = True
                dp_cerrado = False
                dp = xbmcgui.DialogProgressBG()
                dp.create(msg_header)

            else:
                # -- Terminar: ----------------------------------
                # -- Comprobar si el vídeo pertenece a una ------
                # -- lista de archivos                          -
                remove_files(download, torrent_file, video_file, ses, h,
                             ren_video_file)
                dp.close()
                return
                """
                #_index, video_file, video_size, len_files = get_video_files_sizes( info )
                if _index < 0 or len_files == 1:
                    # -- Diálogo eliminar archivos --------------
                    #video_file = _video_file
                    remove_files( download, torrent_file, video_file, ses, h, ren_video_file )
                    dp.close()
                    return
                else:
                    # -- Lista de archivos. Diálogo de opciones -
                    piece_set = set_priority_pieces(h, _index, video_file, video_size,
                                                    porcent4first_pieces, porcent4last_pieces, allocate)
                    is_view=None
                    dp = xbmcgui.DialogProgress()
                    dp.create(msg_header)
                """

        # -- Mostar progeso antes del visionado -----------------
        if is_view != "Ok":
            dp.update(porcent, message, msg_file)

        # -- Se canceló el progreso antes del visionado ---------
        # -- Dar otra oportunidad en background o Terminar                                           -
        if not bkg_user and dp_cerrado and dp.iscanceled():
            dp.close()
            # Preguntamos si el usuario quiere pasar a backgroung
            dialog = xbmcgui.Dialog().yesno(
                msg_header, "¿Borramos los archivo descargados? (incompletos)",
                "Seleccione NO para seguir descargando en segundo plano")
            if not dialog:
                bkg_user = True
                dp_cerrado = False
                dp = xbmcgui.DialogProgressBG()
                dp.create(msg_header)
                if ses_lt: h.set_download_limit(DOWNLOAD_LIMIT)

            else:

                remove_files(download, torrent_file, video_file, ses, h,
                             ren_video_file)
                return
                # -- Comprobar si el vídeo pertenece a una lista de -
                # -- archivos                                       -
                #_index, video_file, video_size, len_files = get_video_files_sizes( info )
                if _index < 0 or len_files == 1:
                    # -- Diálogo eliminar archivos ------------------
                    #video_file = _video_file
                    remove_files(download, torrent_file, video_file, ses, h,
                                 ren_video_file)
                    return
                else:
                    # -- Lista de archivos. Diálogo de opciones -----
                    piece_set = set_priority_pieces(h, _index, video_file,
                                                    video_size,
                                                    porcent4first_pieces,
                                                    porcent4last_pieces,
                                                    allocate)
                    is_view = None
                    dp = xbmcgui.DialogProgress()
                    dp.create(msg_header)

    # -- Kodi - Error? - No debería llegar aquí -----------------
    if is_view == "Ok" and not xbmc.Player().isPlaying():
        dp.close()
        # -- Diálogo eliminar archivos --------------------------
        remove_files(download, torrent_file, video_file, ses, h,
                     ren_video_file)

    return
Ejemplo n.º 11
0
    def service(self):
        ''' If error is encountered, it will rerun this function.
            Start new "daemon threads" to process library updates.
            (actual daemon thread is not supported in Kodi)
        '''
        for threads in (self.download_threads, self.writer_threads['updated'],
                        self.writer_threads['userdata'],
                        self.writer_threads['removed']):
            for thread in threads:
                if thread.is_done:
                    threads.remove(thread)

        if not self.player.isPlayingVideo() or settings(
                'syncDuringPlay.bool') or xbmc.getCondVisibility(
                    'VideoPlayer.Content(livetv)'):

            self.worker_downloads()
            self.worker_sort()

            self.worker_updates()
            self.worker_userdata()
            self.worker_remove()
            self.worker_notify()

        if self.pending_refresh:
            window('jellyfin_sync.bool', True)

            if self.total_updates > self.progress_display:
                queue_size = self.worker_queue_size()

                if self.progress_updates is None:

                    self.progress_updates = xbmcgui.DialogProgressBG()
                    self.progress_updates.create(translate('addon_name'),
                                                 translate(33178))
                    self.progress_updates.update(
                        int((float(self.total_updates - queue_size) /
                             float(self.total_updates)) * 100),
                        message="%s: %s" % (translate(33178), queue_size))
                elif queue_size:
                    self.progress_updates.update(
                        int((float(self.total_updates - queue_size) /
                             float(self.total_updates)) * 100),
                        message="%s: %s" % (translate(33178), queue_size))
                else:
                    self.progress_updates.update(int(
                        (float(self.total_updates - queue_size) /
                         float(self.total_updates)) * 100),
                                                 message=translate(33178))

            if not settings(
                    'dbSyncScreensaver.bool') and self.screensaver is None:

                xbmc.executebuiltin('InhibitIdleShutdown(true)')
                self.screensaver = get_screensaver()
                set_screensaver(value="")

        if (self.pending_refresh and not self.download_threads
                and not self.writer_threads['updated']
                and not self.writer_threads['userdata']
                and not self.writer_threads['removed']):
            self.pending_refresh = False
            self.save_last_sync()
            self.total_updates = 0
            window('jellyfin_sync', clear=True)

            if self.progress_updates:

                self.progress_updates.close()
                self.progress_updates = None

            if not settings(
                    'dbSyncScreensaver.bool') and self.screensaver is not None:

                xbmc.executebuiltin('InhibitIdleShutdown(false)')
                set_screensaver(value=self.screensaver)
                self.screensaver = None

            if xbmc.getCondVisibility('Container.Content(musicvideos)'
                                      ):  # Prevent cursor from moving
                xbmc.executebuiltin('Container.Refresh')
            else:  # Update widgets
                xbmc.executebuiltin('UpdateLibrary(video)')

                if xbmc.getCondVisibility('Window.IsMedia'):
                    xbmc.executebuiltin('Container.Refresh')
Ejemplo n.º 12
0
def scan(way):
    emotion = __addon__.getSetting('emotion')
    __addon__.setSetting('emotion', 'false')
    if way == 1:
        log('Kodi > TV Time')
        pDialog = xbmcgui.DialogProgressBG()
        pDialog.create('Kodi > TV Time', __language__(33906))
        pDialog.update(0, message=__language__(33906))
        tvshowsList = getTvshowList()
        showsSeen = []
        showsNotSeen = []
        cpt = 0
        pc = 0
        total = len(tvshowsList)
        for tvshowList in tvshowsList:
            cpt = cpt + 1
            pc = (cpt * 100) / total
            pDialog.update(pc, message=tvshowList['title'])
            xbmc.sleep(100)
            if tvshowList['seen'] == 1:
                showsSeen.append({
                    'show_id': int(tvshowList['show_id']),
                    'season': tvshowList['season'],
                    'episode': tvshowList['episode']
                })
            elif tvshowList['seen'] == 0 and tvshowList[
                    'season'] == 1 and tvshowList['episode'] == 1:
                showsNotSeen.append({'show_id': int(tvshowList['show_id'])})
        cpt = 1
        pc = 0
        limit = 50
        total = int(len(showsSeen)) + int(len(showsNotSeen))
        if len(showsSeen):
            tempShowsSeen = []
            tempcpt = 1
            pDialog.update(0, message=__language__(33908))
            for showSeen in showsSeen:
                cpt = cpt + 1
                pc = (cpt * 100) / total
                tempShowsSeen.append({
                    'show_id': int(showSeen['show_id']),
                    'season': showSeen['season'],
                    'episode': showSeen['episode']
                })
                tempcpt = tempcpt + 1
                if tempcpt >= limit:
                    log("SaveShowsProgress(*, %s)" % tempShowsSeen)
                    show_progress = SaveShowsProgress(
                        __token__, json.dumps(tempShowsSeen))
                    log("show_progress.is_set=%s" % show_progress.is_set)
                    tempShowsSeen = []
                    tempcpt = 0
                    pDialog.update(pc, message=__language__(33908))
            if tempShowsSeen:
                log("SaveShowsProgress(*, %s)" % tempShowsSeen)
                show_progress = SaveShowsProgress(__token__,
                                                  json.dumps(tempShowsSeen))
                log("show_progress.is_set=%s" % show_progress.is_set)
        if len(showsNotSeen):
            tempShowsNotSeen = []
            tempcpt = 0
            pDialog.update(0, message=__language__(33908))
            for showNotSeen in showsNotSeen:
                cpt = cpt + 1
                pc = (cpt * 100) / total
                tempShowsNotSeen.append(
                    {'show_id': int(showNotSeen['show_id'])})
                tempcpt = tempcpt + 1
                if tempcpt >= limit:
                    log("DeleteShowsProgress(*, %s)" % tempShowsNotSeen)
                    show_progress = DeleteShowsProgress(
                        __token__, json.dumps(tempShowsNotSeen))
                    log("show_progress.is_delete=%s" % show_progress.is_delete)
                    tempShowsNotSeen = []
                    tempcpt = 0
                    cpt = cpt + 1
                    pDialog.update(pc, message=__language__(33908))
            if tempShowsNotSeen:
                log("DeleteShowsProgress(*, %s)" % tempShowsNotSeen)
                show_progress = DeleteShowsProgress(
                    __token__, json.dumps(tempShowsNotSeen))
                log("show_progress.is_delete=%s" % show_progress.is_delete)
                follow_shows = FollowShows(__token__,
                                           json.dumps(tempShowsNotSeen))
                log("follow_shows.is_follow=%s" % follow_shows.is_follow)
        pDialog.update(100, message=__language__(33907))
        xbmcgui.Dialog().ok("Kodi > TV Time", __language__(33907))
    else:
        log('TV Time > Kodi')
        pDialog = xbmcgui.DialogProgressBG()
        pDialog.create('TV Time > Kodi', __language__(33906))
        pDialog.update(0, message=__language__(33906))
        tvshowList = getTvshowList()
        tvshowTimeList = getTvshowTimeList()
        if tvshowList and tvshowTimeList:
            total = len(tvshowList)
            for i in range(0, total):
                for tvshowTime in tvshowTimeList:
                    if int(tvshowList[i]['show_id']) == int(
                            tvshowTime['show_id']):
                        pDialog.update(((100 / total) * (i + 1)),
                                       message=tvshowTime['title'])
                        log('setTvshowProgress(%s, %s, %s)' %
                            (tvshowTime['show_id'], tvshowTime['season'],
                             tvshowTime['episode']))
                        tvshowProgress = setTvshowProgress(
                            tvshowTime['show_id'], tvshowTime['season'],
                            tvshowTime['episode'])
        pDialog.update(100, message=__language__(33907))
        xbmcgui.Dialog().ok("TV Time > Kodi", __language__(33907))
    __addon__.setSetting('emotion', emotion)
    pDialog.close()
Ejemplo n.º 13
0
        if not os.path.isfile(image_path):
            image_path = addon_folder + '/resources/no_image.png'
        li = xbmcgui.ListItem(game[0], iconImage=image_path)
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)

    xbmcplugin.endOfDirectory(addon_handle)

elif mode == 'launch':
    command = args['command'][0]
    parameter = args['parameter'][0]
    os.startfile('steam://%s/%s' % (command, parameter))

elif mode == 'scan':
    if not os.path.isdir(library_folder):
        os.mkdir(library_folder)
    dialog_scan = xbmcgui.DialogProgressBG()
    dialog_scan.create('Scanning library', 'Steam Library')
    games = get_installed_games(addon.getSetting('steam_folder'), dialog_scan)
    dialog_scan.close()
    if addon.getSetting('download_images') == 'true':
        dialog_download = xbmcgui.DialogProgressBG()
        dialog_download.create('Downloading images', 'Steam Library')
        download_game_images(games, dialog_download)
        dialog_download.close()
    write_games_xml(games)
    xbmc.executebuiltin('Notification(Steam Library,Found %i games)' %
                        len(games))

else:
    xbmc.log('Steam Library: unkown mode called: %s' % mode,
             level=xbmc.LOGNOTICE)
Ejemplo n.º 14
0
def download_media(url, path, file_name):
    try:
        progress = int(ADDON.get_setting('down_progress'))
        import urllib2
        request = urllib2.Request(url)
        request.add_header('User-Agent', USER_AGENT)
        request.add_unredirected_header('Host', request.get_host())
        response = urllib2.urlopen(request)

        content_length = 0
        if 'Content-Length' in response.info():
            content_length = int(response.info()['Content-Length'])

        file_name = file_name.replace('.strm', get_extension(url, response))
        full_path = os.path.join(path, file_name)
        log_utils.log('Downloading: %s -> %s' % (url, full_path), xbmc.LOGDEBUG)

        path = xbmc.makeLegalFilename(path)
        if not xbmcvfs.exists(path):
            try:
                try: xbmcvfs.mkdirs(path)
                except: os.mkdir(path)
            except Exception as e:
                raise Exception(i18n('failed_create_dir'))

        file_desc = xbmcvfs.File(full_path, 'w')
        total_len = 0
        if progress:
            if progress == PROGRESS.WINDOW:
                dialog = xbmcgui.DialogProgress()
            else:
                dialog = xbmcgui.DialogProgressBG()

            dialog.create('Stream All The Sources', i18n('downloading') % (file_name))
            dialog.update(0)
        while True:
            data = response.read(CHUNK_SIZE)
            if not data:
                break

            if progress == PROGRESS.WINDOW and dialog.iscanceled():
                break

            total_len += len(data)
            if not file_desc.write(data):
                raise Exception('failed_write_file')

            percent_progress = (total_len) * 100 / content_length if content_length > 0 else 0
            log_utils.log('Position : %s / %s = %s%%' % (total_len, content_length, percent_progress), xbmc.LOGDEBUG)
            if progress == PROGRESS.WINDOW:
                dialog.update(percent_progress)
            elif progress == PROGRESS.BACKGROUND:
                dialog.update(percent_progress, 'Stream All The Sources')
        else:
            notify(msg=i18n('download_complete') % (file_name), duration=5000)
            log_utils.log('Download Complete: %s -> %s' % (url, full_path), xbmc.LOGDEBUG)

        file_desc.close()
        if progress:
            dialog.close()

    except Exception as e:
        log_utils.log('Error (%s) during download: %s -> %s' % (str(e), url, file_name), xbmc.LOGERROR)
        notify(msg=i18n('download_error') % (str(e), file_name), duration=5000)
Ejemplo n.º 15
0
 def DialogProgressBG_Create(self, *args, **kwargs):
     dialog = xbmcgui.DialogProgressBG()
     self._objects[id(dialog)] = dialog
     dialog.create(*args, **kwargs)
     return id(dialog)
Ejemplo n.º 16
0
 def remove_like(self, pattern, notify=True):
     """
     Removes cached items with urls LIKE pattern
         from sqlite database(Textures13.db) and deletes cached image
     :param pattern: string: an sqlite LIKE pattern of image url(s) to be removed
     :param notify: bool: enable/disable informational notifications
     :return:
     """
     if xbmcvfs.exists(self.DATABASE):
         connection = sqlite3.connect(self.DATABASE)
         connection.isolation_level = None
         cursor = connection.cursor()
         dialog = None
         thumbnails = list()
         if notify:
             dialog = xbmcgui.DialogProgressBG()
             dialog.create(self.NAME + ' Cache Removal',
                           'Removing cached items ...')
         try:
             cursor.execute('BEGIN')
             cursor.execute(
                 'SELECT id, cachedurl FROM texture WHERE url LIKE "{0}"'.
                 format(pattern))
             rows_list = cursor.fetchall()
             row_count = len(rows_list)
             percent = 100 / (row_count + 5)
             if row_count > 0:
                 for index, row in enumerate(rows_list):
                     if dialog:
                         dialog.update(
                             percent * (index + 1),
                             message='Removing cached item ... {0}'.format(
                                 row[1]))
                     thumbnail_path = xbmc.translatePath(
                         "special://thumbnails/{0}".format(row[1]))
                     cursor.execute(
                         'DELETE FROM sizes WHERE idtexture LIKE "{0}"'.
                         format(row[0]))
                     if xbmcvfs.exists(thumbnail_path):
                         thumbnails.append(thumbnail_path)
                 if dialog:
                     dialog.update(
                         percent * (row_count + 1),
                         message='Removing cached items from texture ...')
                 cursor.execute(
                     'DELETE FROM texture WHERE url LIKE "{0}"'.format(
                         pattern))
             if dialog:
                 dialog.update(percent * (row_count + 2),
                               message='Committing ...')
                 cursor.execute('COMMIT')
                 dialog.update(percent * (row_count + 3),
                               message='Recovering free space ...')
                 cursor.execute('VACUUM')
                 dialog.update(percent * (row_count + 4),
                               message='Committing ...')
                 connection.commit()
                 dialog.update(100, message='Cached items removed')
             else:
                 cursor.execute('COMMIT')
                 cursor.execute('VACUUM')
                 connection.commit()
         except:
             if dialog:
                 dialog.close()
             thumbnails = list()
             message = 'Error removing cached items, rolling back ...'
             self.notification(message, sound=True)
             xbmc.log(message, xbmc.LOGDEBUG)
             connection.rollback()
         finally:
             cursor.close()
             connection.close()
             if thumbnails:
                 percent = 100 / len(thumbnails)
                 for index, thumb in enumerate(thumbnails):
                     if dialog:
                         dialog.update(
                             percent * (index + 1),
                             message='Deleting cached item ... {0}'.format(
                                 thumb))
                     try:
                         xbmcvfs.delete(thumb)
                     except:
                         try:
                             os.remove(thumb)
                         except:
                             message = 'Failed to delete |{0}|'.format(
                                 thumb)
                             xbmc.log(message, xbmc.LOGERROR)
             if dialog:
                 dialog.close()
     else:
         message = 'Database not found ({0})'.format(self.DATABASE)
         self.notification(message)
         xbmc.log(message, xbmc.LOGDEBUG)
def do_search(item):
    logger.info("streamondemand-pureita-master.channels.buscador do_search")

    tecleado = item.extra
    mostra = tecleado.replace("+", " ")

    itemlist = []

    channels_path = os.path.join(config.get_runtime_path(), "channels",
                                 '*.xml')
    logger.info(
        "streamondemand-pureita-master.channels.buscador channels_path=" +
        channels_path)

    channel_language = config.get_setting("channel_language")
    logger.info(
        "streamondemand-pureita-master.channels.buscador channel_language=" +
        channel_language)
    if channel_language == "":
        channel_language = "all"
        logger.info(
            "streamondemand-pureita-master.channels.buscador channel_language="
            + channel_language)

    if config.is_xbmc():
        show_dialog = True

    try:
        import xbmcgui
        progreso = xbmcgui.DialogProgressBG()
        progreso.create("Ricerca di " + mostra.title())
    except:
        show_dialog = False

    def worker(infile, queue):
        channel_result_itemlist = []
        try:
            basename_without_extension = os.path.basename(infile)[:-4]
            # http://docs.python.org/library/imp.html?highlight=imp#module-imp
            obj = imp.load_source(basename_without_extension,
                                  infile[:-4] + ".py")
            logger.info(
                "streamondemand-pureita-master.channels.buscador cargado " +
                basename_without_extension + " de " + infile)
            channel_result_itemlist.extend(
                obj.search(Item(extra=item.category), tecleado))
            for local_item in channel_result_itemlist:
                local_item.title = " [COLOR azure] " + local_item.title + " [/COLOR] [COLOR orange]su[/COLOR] [COLOR orange]" + basename_without_extension + "[/COLOR]"
                local_item.viewmode = "list"
        except:
            import traceback
            logger.error(traceback.format_exc())
        queue.put(channel_result_itemlist)

    channel_files = glob.glob(channels_path)

    channel_files_tmp = []
    for infile in channel_files:

        basename_without_extension = os.path.basename(infile)[:-4]

        channel_parameters = channeltools.get_channel_parameters(
            basename_without_extension)

        # No busca si es un canal inactivo
        if channel_parameters["active"] != "true":
            continue

        # No busca si es un canal excluido de la busqueda global
        if channel_parameters["include_in_global_search"] != "true":
            continue

        # No busca si es un canal para adultos, y el modo adulto está desactivado
        if channel_parameters["adult"] == "true" and config.get_setting(
                "adult_mode") == "false":
            continue

        # No busca si el canal es en un idioma filtrado
        if channel_language != "all" and channel_parameters[
                "language"] != channel_language:
            continue

        channel_files_tmp.append(infile)

    channel_files = channel_files_tmp

    result = Queue.Queue()
    threads = [
        threading.Thread(target=worker, args=(infile, result))
        for infile in channel_files
    ]

    start_time = int(time.time())

    for t in threads:
        t.daemon = True  # NOTE: setting dameon to True allows the main thread to exit even if there are threads still running
        t.start()

    number_of_channels = len(channel_files)
    completed_channels = 0
    while completed_channels < number_of_channels:

        delta_time = int(time.time()) - start_time
        if len(itemlist) <= 0:
            timeout = None  # No result so far,lets the thread to continue working until a result is returned
        elif delta_time >= TIMEOUT_TOTAL:
            break  # At least a result matching the searched title has been found, lets stop the search
        else:
            timeout = TIMEOUT_TOTAL - delta_time  # Still time to gather other results

        if show_dialog:
            progreso.update(completed_channels * 100 / number_of_channels)

        try:
            result_itemlist = result.get(timeout=timeout)
            completed_channels += 1
        except:
            # Expired timeout raise an exception
            break

        for item in result_itemlist:
            title = item.fulltitle

            # Clean up a bit the returned title to improve the fuzzy matching
            title = re.sub(r'\(.*\)', '', title)  # Anything within ()
            title = re.sub(r'\[.*\]', '', title)  # Anything within []

            # Check if the found title fuzzy matches the searched one
            if fuzz.WRatio(mostra, title) > 85: itemlist.append(item)

    if show_dialog:
        progreso.close()

    itemlist = sorted(itemlist, key=lambda item: item.fulltitle)

    return itemlist
Ejemplo n.º 18
0
 def initDialog(self):
     self.dialog = xbmcgui.DialogProgressBG()
def doDownload(url, dest, title, referer, agent, cookie):
    file = dest.rsplit(os.sep, 1)[-1].split('-.')[0]

    resp = getResponse(url, 0, referer, agent, cookie)

    if not resp:
        xbmcgui.Dialog().ok(title, dest, 'Download falhou',
                            'Sem resposta do servidor')
        return

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

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

    #print "Download Header"
    #print resp.headers
    if resumable:
        print "Download e resumivel"

    if content < 1:
        xbmcgui.Dialog().ok(title, file, 'Tamanho do ficheiro desconhecido.',
                            'Impossível fazer download.')
        return

    size = 1024 * 1024
    mb = content / (1024 * 1024)

    if content < size:
        size = content

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

    if xbmcgui.Dialog().yesno(title, file,
                              'Ficheiro completo ocupa %dMB.' % mb,
                              'Continuar com o download?'):
        pass
    else:
        return
    print 'Download File Size : %dMB %s ' % (mb, dest)

    dialogDL = dialogCompatible()  #dialog available on gotham++

    #f = open(dest, mode='wb')
    f = xbmcvfs.File(dest, 'w')

    chunk = None
    chunks = []
    if dialogDL == True:
        pDialog = xbmcgui.DialogProgressBG()
        pDialog.create(title, file)

    while True:
        downloaded = total
        for c in chunks:
            downloaded += len(c)
        percent = min(100 * downloaded / content, 100)
        if percent >= notify:
            if dialogDL == False:
                xbmc.executebuiltin("XBMC.Notification(%s,%s,%i,%s)" %
                                    (title + ' - ' + str(percent) + '%', file,
                                     10000, iconpequeno))
            else:
                pDialog.update(percent)
            print 'Download percent : %s %s %dMB downloaded : %sMB File Size : %sMB' % (
                str(percent) + '%', dest, mb, downloaded / 1000000,
                content / 1000000)
            notify += 10

        if dialogDL == True: pDialog.update(percent)
        chunk = None
        error = False

        try:
            chunk = resp.read(size)
            if not chunk:
                if dialogDL == True: pDialog.close()
                if 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)
                    if not xbmc.Player().isPlaying():
                        xbmcgui.Dialog().ok(title, file, '',
                                            'Download concluído')
                    return
        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)
            xbmc.sleep(sleep * 1000)

        if (resumable and errors > 0) or errors >= 10:
            if (not resumable and resume >= 10) or resume >= 100:
                #Give up!
                print '%s download canceled - too many error whilst downloading' % (
                    dest)
                xbmcgui.Dialog().ok(title, file, '', 'Download falhou')
                return

            resume += 1
            errors = 0
            if resumable:
                chunks = []
                #create new response
                print 'Download resumed (%d) %s' % (resume, dest)
                resp = getResponse(url, total, referer, agent, cookie)
            else:
                #use existing response
                pass
Ejemplo n.º 20
0
    def fetchFile(self, force=False):
        retVal = self.FETCH_NOT_NEEDED
        fetch = False
        if not os.path.exists(
                self.filePath):  # always fetch if file doesn't exist!
            fetch = True
        elif force == True:
            fetch = True
        else:
            interval = int(self.addon.getSetting('xmltv.interval'))
            if interval != self.INTERVAL_ALWAYS:
                modTime = datetime.datetime.fromtimestamp(
                    os.path.getmtime(self.filePath))
                td = datetime.datetime.now() - modTime
                # need to do it this way cause Android doesn't support .total_seconds() :(
                diff = (td.microseconds +
                        (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
                if ((interval == self.INTERVAL_12 and diff >= 43200)
                        or (interval == self.INTERVAL_24 and diff >= 86400)
                        or (interval == self.INTERVAL_48 and diff >= 172800)
                        or (interval == self.INTERVAL_7 and diff >= 604800)
                        or (interval == self.INTERVAL_14 and diff >= 1209600)):
                    fetch = True
            else:
                fetch = True

        if fetch:
            user = ''
            password = ''
            new_md5 = ''
            auth = None
            if self.addon.getSetting('authentication') == 'true':
                user = self.addon.getSetting('user')
                password = self.addon.getSetting('password')
                auth = (user, password)
            tmpFile = os.path.join(self.basePath, self.fileName + '.tmp')
            if self.fileType == self.TYPE_DEFAULT:
                xbmc.log(
                    '[script.tvguide.Vader] file is in remote location: %s' %
                    self.fileUrl, xbmc.LOGDEBUG)
                if xbmcvfs.exists(self.filePath):
                    st = xbmcvfs.Stat(self.fileUrl)
                    src_modified = st.st_mtime()
                    st = xbmcvfs.Stat(self.filePath)
                    dst_modified = st.st_mtime()
                    if src_modified <= dst_modified:
                        return self.FETCH_NOT_NEEDED
                if not xbmcvfs.copy(self.fileUrl, tmpFile):
                    xbmc.log(
                        '[script.tvguide.Vader] Remote file couldn\'t be copied: %s'
                        % self.fileUrl, xbmc.LOGERROR)
            else:

                if self.addon.getSetting('md5') == 'true':
                    file = self.filePath + ".md5"
                    url = self.fileUrl + ".md5"
                    old_md5 = xbmcvfs.File(file, "rb").read()
                    try:
                        r = requests.get(url, auth=auth)
                        if r.status_code == requests.codes.ok:
                            new_md5 = r.text.encode('ascii', 'ignore')[:32]
                    except Exception as detail:
                        xbmc.log(
                            '[script.tvguide.Vader] Missing md5: %s.md5 (%s)' %
                            (self.fileUrl, detail), xbmc.LOGERROR)
                    #log((old_md5,new_md5))
                    if old_md5 and (old_md5 == new_md5) and (
                            self.addon.getSetting('xmltv.refresh') == 'false'):
                        return self.FETCH_NOT_NEEDED
                f = open(tmpFile, 'wb')
                xbmc.log(
                    '[script.tvguide.Vader] file is on the internet: %s' %
                    self.fileUrl, xbmc.LOGDEBUG)
                total = 0
                fileUrl = self.fileUrl
                if ADDON.getSetting('gz') == 'true':
                    fileUrl = fileUrl + '.gz'
                try:
                    r = requests.get(fileUrl,
                                     auth=auth,
                                     stream=True,
                                     verify=False)
                    if r.status_code != requests.codes.ok:
                        if ADDON.getSetting('gz') == 'true':
                            r = requests.get(self.fileUrl,
                                             auth=auth,
                                             stream=True,
                                             verify=False)
                            if r.status_code != requests.codes.ok:
                                xbmc.log(
                                    '[script.tvguide.Vader] no file: %s' %
                                    self.fileUrl, xbmc.LOGERROR)
                                xbmcgui.Dialog().notification(
                                    "TV Guide",
                                    "bad status code %s" % self.fileUrl,
                                    xbmcgui.NOTIFICATION_ERROR)
                        else:
                            xbmc.log(
                                '[script.tvguide.Vader] no file: %s' % fileUrl,
                                xbmc.LOGERROR)
                            xbmcgui.Dialog().notification(
                                "TV Guide", "bad status code %s " % fileUrl,
                                xbmcgui.NOTIFICATION_ERROR)
                            return self.FETCH_NOT_NEEDED
                    if "Content-Length" in r.headers:
                        total = int(r.headers['Content-Length'])
                except Exception as detail:
                    xbmc.log(
                        '[script.tvguide.Vader] bad request: %s (%s)' %
                        (fileUrl, detail), xbmc.LOGERROR)
                    xbmcgui.Dialog().notification(
                        "TV Guide", "failed to download %s " % fileUrl,
                        xbmcgui.NOTIFICATION_ERROR)
                    return self.FETCH_NOT_NEEDED

                title = fileUrl.split('/')[-1]
                if os.path.exists(self.filePath):
                    try:
                        os.remove(self.filePath)
                    except:
                        pass
            md5_pass = 0
            while md5_pass == 0:
                d = xbmcgui.DialogProgressBG()
                d.create('TV Guide', 'downloading guide data')
                chunk_size = 16 * 1024
                size = 0
                oldtime = time.time()
                for chunk in r.iter_content(chunk_size):
                    f.write(chunk)
                    size = size + chunk_size
                    if total:
                        percent = 100.0 * size / total
                        now = time.time()
                        diff = now - oldtime
                        if diff > 1:
                            d.update(int(percent))
                            oldtime = now
                f.close()
                d.update(100, message="Done")
                d.close()
                if os.path.exists(self.filePath):
                    try:
                        os.remove(self.filePath)
                    except:
                        return self.FETCH_NOT_NEEDED
                try:
                    magic = xbmcvfs.File(tmpFile, "rb").read(3)
                    if magic == "\x1f\x8b\x08":
                        g = gzip.open(tmpFile)
                        data = g.read()
                        xbmcvfs.File(self.filePath, "wb").write(data)
                    else:
                        xbmcvfs.copy(tmpFile, self.filePath)
                    xbmcvfs.delete(tmpFile)
                except:
                    return self.FETCH_NOT_NEEDED
                if new_md5 and (self.addon.getSetting('md5') == 'true'):
                    md5 = hashlib.md5()
                    md5.update(xbmcvfs.File(self.filePath, "rb").read())
                    md5_file = md5.hexdigest()
                    if md5_file != new_md5:
                        xbmc.log(
                            '[script.tvguide.Vader] md5 mismatch: %s calculated:%s server:%s'
                            % (self.fileUrl, md5_file, new_md5), xbmc.LOGERROR)
                        choice = xbmcgui.Dialog().yesno(
                            "V Guide",
                            "Failed md5 check. Would you like to try again?")
                        if choice == 0:
                            try:
                                shutil.rmtree(basePath)
                            except:
                                pass
                            sys.exit(0)
                    else:
                        md5_pass = 1
                else:
                    md5_pass = 1
            retVal = self.FETCH_OK
            xbmc.log(
                '[script.tvguide.Vader] file %s was downloaded' %
                self.filePath, xbmc.LOGDEBUG)
        return retVal
Ejemplo n.º 21
0
    url = "https://pixabay.com/api/?key=3974133-0e761ef66bcfb72c6a8ac8f4e&q=%s&image_type=photo&pretty=true&orientation=horizontal&per_page=200" % what
    r = requests.get(url)
    j = json.loads(r.content)
    if not 'hits' in j:
        quit()

    dirs, files = xbmcvfs.listdir(
        'special://profile/addon_data/script.stargate.guide/pick/')
    for f in files:
        path = 'special://profile/addon_data/script.stargate.guide/pick/' + f
        success = xbmcvfs.delete(path)

    hits = j['hits']
    images = {}
    p = xbmcgui.DialogProgressBG()
    p.create("Finding Images", "...")
    total = len(hits)
    i = 0
    for h in hits:
        url = h["previewURL"].replace(': //', '://')
        basename = url.rsplit('/', 1)[-1]
        localfile = 'special://profile/addon_data/script.stargate.guide/pick/' + basename
        xbmcvfs.copy(url, localfile)
        image = h["webformatURL"].replace(': //', '://')
        if image:
            images[localfile] = image
        percent = 100.0 * i / total
        i = i + 1
        p.update(int(percent), "Finding Images", basename)
    p.close()
Ejemplo n.º 22
0
def search(payload, method="general"):
    """ Main search entrypoint

    Args:
        payload (dict): Search payload from Elementum.
        method   (str): Type of search, can be ``general``, ``movie``, ``show``, ``season`` or ``anime``

    Returns:
        list: All filtered results in the format Elementum expects
    """
    log.debug("Searching with payload (%s): %s" % (method, repr(payload)))

    if method == 'general':
        if 'query' in payload:
            payload['title'] = payload['query']
            payload['titles'] = {'source': payload['query']}
        else:
            payload = {
                'title': payload,
                'titles': {
                    'source': payload
                },
            }

    payload['titles'] = dict(
        (k.lower(), v) for k, v in payload['titles'].iteritems())

    # If titles[] exists in payload and there are special chars in titles[source]
    #   then we set a flag to possibly modify the search query
    payload['has_special'] = 'titles' in payload and \
                             bool(payload['titles']) and \
                             'source' in payload['titles'] and \
                             any(c in payload['titles']['source'] for c in special_chars)
    if payload['has_special']:
        log.debug(
            "Query title contains special chars, so removing any quotes in the search query"
        )

    global request_time
    global provider_names
    global provider_results
    global available_providers

    provider_names = []
    provider_results = []
    available_providers = 0
    request_time = time.time()

    providers = get_enabled_providers(method)

    if len(providers) == 0:
        notify(translation(32060), image=get_icon_path())
        log.error("No providers enabled")
        return []

    log.info(
        "Burstin' with %s" %
        ", ".join([definitions[provider]['name'] for provider in providers]))

    if get_setting("use_cloudhole", bool):
        clearance, user_agent = get_cloudhole_clearance(get_cloudhole_key())
        set_setting('clearance', clearance)
        set_setting('user_agent', user_agent)

    if get_setting('kodi_language', bool):
        kodi_language = xbmc.getLanguage(xbmc.ISO_639_1)
        if not kodi_language:
            log.warning("Kodi returned empty language code...")
        elif 'titles' not in payload or not payload['titles']:
            log.info("No translations available...")
        elif payload['titles'] and kodi_language not in payload['titles']:
            log.info("No '%s' translation available..." % kodi_language)

    p_dialog = xbmcgui.DialogProgressBG()
    p_dialog.create('Elementum [COLOR FFFF6B00]Burst[/COLOR]',
                    translation(32061))
    for provider in providers:
        available_providers += 1
        provider_names.append(definitions[provider]['name'])
        task = Thread(target=run_provider, args=(provider, payload, method))
        task.start()

    providers_time = time.time()
    total = float(available_providers)

    # Exit if all providers have returned results or timeout reached, check every 100ms
    while time.time() - providers_time < timeout and available_providers > 0:
        timer = time.time() - providers_time
        log.debug("Timer: %ds / %ds" % (timer, timeout))
        if timer > timeout:
            break
        message = translation(
            32062
        ) % available_providers if available_providers > 1 else translation(
            32063)
        p_dialog.update(int((total - available_providers) / total * 100),
                        message=message)
        time.sleep(0.25)

    p_dialog.close()
    del p_dialog

    if available_providers > 0:
        message = u', '.join(provider_names)
        message = message + translation(32064)
        log.warning(message.encode('utf-8'))
        notify(message, ADDON_ICON)

    log.debug("all provider_results: %s" % repr(provider_results))

    filtered_results = apply_filters(provider_results)

    log.debug("all filtered_results: %s" % repr(filtered_results))

    log.info("Providers returned %d results in %s seconds" %
             (len(filtered_results), round(time.time() - request_time, 2)))

    return filtered_results
Ejemplo n.º 23
0
 def progress_start(self, count):
     import xbmcgui
     self._progress = xbmcgui.DialogProgressBG()
     self._progress.create(_addon_name)
     self._progress_count = count
def download_multithread(thread_temppath, download_threads, grabber,
                         hzn_chlist_selected, provider, provider_temppath,
                         hzndict, days_to_grab):
    # delete old broadcast files if exist
    for f in os.listdir(provider_temppath):
        if f.endswith('_broadcast.json'):
            xbmcvfs.delete(os.path.join(provider_temppath, f))

    list = os.path.join(provider_temppath, 'list.txt')
    splitname = os.path.join(thread_temppath, 'chlist_hznXX_selected')
    starttime, endtime = get_epgLength(days_to_grab)

    with open(hzn_chlist_selected, 'r', encoding='utf-8') as s:
        selected_list = json.load(s)

    if filesplit.split_chlist_selected(thread_temppath, hzn_chlist_selected,
                                       splitname, download_threads,
                                       enable_multithread):
        multi = True
        needed_threads = sum(
            [len(files) for r, d, files in os.walk(thread_temppath)])
        items_to_download = str(len(selected_list['channellist']))
        log('{} {} {} '.format(provider, items_to_download, loc(32361)),
            xbmc.LOGNOTICE)
        pDialog = xbmcgui.DialogProgressBG()
        log('{} Multithread({}) Mode'.format(provider, needed_threads),
            xbmc.LOGNOTICE)
        pDialog.create('{} {} '.format(loc(32500), provider),
                       '{} {}'.format('100', loc(32501)))

        jobs = []
        for thread in range(0, int(needed_threads)):
            p = Process(target=download_thread,
                        args=(
                            grabber,
                            '{}_{}.json'.format(splitname, int(thread)),
                            multi,
                            list,
                            provider,
                            provider_temppath,
                            hzndict,
                            days_to_grab,
                            starttime,
                            endtime,
                        ))
            jobs.append(p)
            p.start()
        for j in jobs:
            while j.is_alive():
                xbmc.sleep(500)
                try:
                    last_line = ''
                    with open(list, 'r', encoding='utf-8') as f:
                        last_line = f.readlines()[-1]
                except:
                    pass
                items = sum(1 for f in os.listdir(provider_temppath)
                            if f.endswith('_broadcast.json'))
                percent_remain = int(
                    100) - int(items) * int(100) / int(items_to_download)
                percent_completed = int(100) * int(items) / int(
                    items_to_download)
                pDialog.update(
                    int(percent_completed),
                    '{} {} '.format(loc(32500), last_line),
                    '{} {} {}'.format(int(percent_remain), loc(32501),
                                      provider))
                if int(items) == int(items_to_download):
                    log('{} {}'.format(provider, loc(32363)), xbmc.LOGNOTICE)
                    break
            j.join()
        pDialog.close()
        for file in os.listdir(thread_temppath):
            xbmcvfs.delete(os.path.join(thread_temppath, file))
    else:
        multi = False
        download_thread(grabber, hzn_chlist_selected, multi, list, provider,
                        provider_temppath, hzndict, days_to_grab, starttime,
                        endtime)
Ejemplo n.º 25
0
    def onInit(self):
        self.log('onInit')

        if FileAccess.exists(GEN_CHAN_LOC) == False:
            try:
                FileAccess.makedirs(GEN_CHAN_LOC)
            except:
                self.Error(LANGUAGE(30035))
                return

        if FileAccess.exists(MADE_CHAN_LOC) == False:
            try:
                FileAccess.makedirs(MADE_CHAN_LOC)
            except:
                self.Error(LANGUAGE(30036))
                return
                
        if FileAccess.exists(CHANNELBUG_LOC) == False:
                try:
                    FileAccess.makedirs(CHANNELBUG_LOC)
                except:
                    self.Error(LANGUAGE(30036))
                    return

        self.getControl(102).setVisible(False)
        self.backupFiles()
        ADDON_SETTINGS.loadSettings()
        
        if CHANNEL_SHARING:
            updateDialog = xbmcgui.DialogProgressBG()
            updateDialog.create(ADDON_NAME, '')
            updateDialog.update(1, message='Initializing Channel Sharing')
            FileAccess.makedirs(LOCK_LOC)
            updateDialog.update(50, message='Initializing Channel Sharing')
            self.isMaster = GlobalFileLock.lockFile("MasterLock", False)
            updateDialog.update(100, message='Initializing Channel Sharing')
            xbmc.sleep(200)
            updateDialog.close()
        else:
            self.isMaster = True

        if self.isMaster:
            migratemaster = Migrate()
            migratemaster.migrate()

        self.channelLabelTimer = threading.Timer(3.0, self.hideChannelLabel)
        self.playerTimer = threading.Timer(2.0, self.playerTimerAction)
        self.playerTimer.name = "PlayerTimer"
        self.infoTimer = threading.Timer(5.0, self.hideInfo)
        self.myEPG = EPGWindow("script.pseudotv.EPG.xml", CWD, "default")
        self.myEPG.MyOverlayWindow = self
        # Don't allow any actions during initialization
        self.actionSemaphore.acquire()
        self.timeStarted = time.time()

        if self.readConfig() == False:
            return

        self.myEPG.channelLogos = self.channelLogos
        self.maxChannels = len(self.channels)

        if self.maxChannels == 0:
            self.Error(LANGUAGE(30037))
            return

        found = False

        for i in range(self.maxChannels):
            if self.channels[i].isValid:
                found = True
                break

        if found == False:
            self.Error(LANGUAGE(30038))
            return

        if self.sleepTimeValue > 0:
            self.sleepTimer = threading.Timer(self.sleepTimeValue, self.sleepAction)

        self.notificationTimer = threading.Timer(NOTIFICATION_CHECK_TIME, self.notificationAction)

        try:
            if self.forceReset == False:
                self.currentChannel = self.fixChannel(int(ADDON.getSetting("CurrentChannel")))
            else:
                self.currentChannel = self.fixChannel(1)
        except:
            self.currentChannel = self.fixChannel(1)

        self.resetChannelTimes()
        self.setChannel(self.currentChannel)
        self.startSleepTimer()
        self.startNotificationTimer()
        self.playerTimer.start()

        if self.backgroundUpdating < 2 or self.isMaster == False:
            self.channelThread.name = "ChannelThread"
            self.channelThread.start()

        self.actionSemaphore.release()
        self.log('onInit return')
def create_xml_broadcast(grabber, enable_rating_mapper, thread_temppath,
                         download_threads):
    provider_temppath, hzn_genres_json, hzn_channels_json, hzn_genres_warnings_tmp, hzn_genres_warnings, hzn_channels_warnings_tmp, hzn_channels_warnings, days_to_grab, episode_format, channel_format, genre_format, hzn_chlist_provider_tmp, hzn_chlist_provider, hzn_chlist_selected, provider, lang = get_settings(
        grabber)
    hzndict = get_hzndict(grabber)

    download_multithread(thread_temppath, download_threads, grabber,
                         hzn_chlist_selected, provider, provider_temppath,
                         hzndict, days_to_grab)
    log('{} {}'.format(provider, loc(32365)), xbmc.LOGNOTICE)

    if genre_format == 'eit':
        ## Save hzn_genres.json to Disk
        genres_file = requests.get(hzn_genres_url).json()
        with open(hzn_genres_json, 'w', encoding='utf-8') as genres_list:
            json.dump(genres_file, genres_list)

    with open(hzn_chlist_selected, 'r', encoding='utf-8') as c:
        selected_list = json.load(c)

    items_to_download = str(len(selected_list['channellist']))
    items = 0
    pDialog = xbmcgui.DialogProgressBG()
    pDialog.create('{} {} '.format(loc(32503), provider),
                   '{} Prozent verbleibend'.format('100'))

    ## Create XML Broadcast Provider information
    xml_structure.xml_broadcast_start(provider)

    for user_item in selected_list['channellist']:
        items += 1
        percent_remain = int(
            100) - int(items) * int(100) / int(items_to_download)
        percent_completed = int(100) * int(items) / int(items_to_download)
        contentID = user_item['contentId']
        channel_name = user_item['name']
        channel_id = channel_name
        pDialog.update(
            int(percent_completed), '{} {} '.format(loc(32503), channel_name),
            '{} {} {}'.format(int(percent_remain), loc(32501), provider))
        if str(percent_completed) == str(100):
            log('{} {}'.format(provider, loc(32366)), xbmc.LOGNOTICE)

        broadcast_files = os.path.join(provider_temppath,
                                       '{}_broadcast.json'.format(contentID))
        with open(broadcast_files, 'r', encoding='utf-8') as b:
            broadcastfiles = json.load(b)

        ### Map Channels
        if not channel_id == '':
            channel_id = mapper.map_channels(channel_id, channel_format,
                                             hzn_channels_json,
                                             hzn_channels_warnings_tmp, lang)

        try:
            for playbilllist in broadcastfiles['listings']:
                try:
                    item_title = playbilllist['program']['title']
                except (KeyError, IndexError):
                    item_title = ''
                try:
                    item_starttime = playbilllist['startTime']
                except (KeyError, IndexError):
                    item_starttime = ''
                try:
                    item_endtime = playbilllist['endTime']
                except (KeyError, IndexError):
                    item_endtime = ''
                try:
                    item_description = playbilllist['program'][
                        'longDescription']
                except (KeyError, IndexError):
                    item_description = ''
                try:
                    item_picture = 'https://www.staticwhich.co.uk/static/images/products/no-image/no-image-available.png'
                    found = False
                    asset_types = [
                        'HighResPortrait', 'boxart-xlarge', 'boxart-large',
                        'boxart-medium', 'tva-poster', 'tva-boxcover'
                    ]
                    for asset_type in asset_types:
                        for i in range(0,
                                       len(playbilllist['program']['images'])):
                            if playbilllist['program']['images'][i][
                                    'assetType'] == asset_type:
                                item_picture = playbilllist['program'][
                                    'images'][i]['url']
                                found = True
                                break
                        if found: break
                    item_picture = item_picture.split('?w')
                    item_picture = item_picture[0]
                except (KeyError, IndexError):
                    item_picture = 'https://www.staticwhich.co.uk/static/images/products/no-image/no-image-available.png'
                try:
                    item_subtitle = playbilllist['program']['secondaryTitle']
                except (KeyError, IndexError):
                    item_subtitle = ''
                genres_list = list()
                try:
                    genre_1 = playbilllist['program']['categories'][0][
                        'title'].replace(',', '')
                    genres_list.append(genre_1)
                except (KeyError, IndexError):
                    genre_1 = ''
                try:
                    genre_2 = playbilllist['program']['categories'][1][
                        'title'].replace(',', '')
                    genres_list.append(genre_2)
                except (KeyError, IndexError):
                    genre_2 = ''
                try:
                    genre_3 = playbilllist['program']['categories'][2][
                        'title'].replace(',', '')
                    genres_list.append(genre_3)
                except (KeyError, IndexError):
                    genre_3 = ''
                try:
                    items_genre = ','.join(genres_list)
                except (KeyError, IndexError):
                    items_genre = ''
                try:
                    item_date = playbilllist['program']['year']
                except (KeyError, IndexError):
                    item_date = ''
                try:
                    item_season = playbilllist['program']['seriesNumber']
                except (KeyError, IndexError):
                    item_season = ''
                try:
                    item_episode = playbilllist['program'][
                        'seriesEpisodeNumber']
                except (KeyError, IndexError):
                    item_episode = ''
                try:
                    item_agerating = playbilllist['program']['parentalRating']
                except (KeyError, IndexError):
                    item_agerating = ''
                try:
                    items_director = ','.join(
                        playbilllist['program']['directors'])
                except (KeyError, IndexError):
                    items_director = ''
                try:
                    items_actor = ','.join(playbilllist['program']['cast'])
                except (KeyError, IndexError):
                    items_actor = ''

                # Transform items to Readable XML Format
                item_starrating = ''
                item_country = ''
                items_producer = ''
                if item_agerating == '-1':
                    item_agerating = ''

                if not item_season == '':
                    if int(item_season) > 999:
                        item_season = ''
                if not item_episode == '':
                    if int(item_episode) > 99999:
                        item_episode = ''

                item_starttime = datetime.utcfromtimestamp(
                    item_starttime / 1000).strftime('%Y%m%d%H%M%S')
                item_endtime = datetime.utcfromtimestamp(
                    item_endtime / 1000).strftime('%Y%m%d%H%M%S')

                # Map Genres
                if not items_genre == '':
                    items_genre = mapper.map_genres(items_genre, genre_format,
                                                    hzn_genres_json,
                                                    hzn_genres_warnings_tmp,
                                                    lang)

                ## Create XML Broadcast Information with provided Variables
                xml_structure.xml_broadcast(
                    episode_format,
                    channel_id, item_title, str(item_starttime),
                    str(item_endtime), item_description, item_country,
                    item_picture, item_subtitle, items_genre, item_date,
                    item_season, item_episode, item_agerating, item_starrating,
                    items_director, items_producer, items_actor,
                    enable_rating_mapper, lang)

        except (KeyError, IndexError):
            log('{} {} {} {} {} {}'.format(provider, loc(32367), channel_name,
                                           loc(32368), contentID, loc(32369)))
    pDialog.close()

    ## Create Channel Warnings Textile
    channel_pull = '\nPlease Create an Pull Request for Missing Rytec Id´s to https://github.com/sunsettrack4/config_files/blob/master/hzn_channels.json\n'
    mapper.create_channel_warnings(hzn_channels_warnings_tmp,
                                   hzn_channels_warnings, provider,
                                   channel_pull)

    ## Create Genre Warnings Textfile
    genre_pull = '\nPlease Create an Pull Request for Missing EIT Genres to https://github.com/sunsettrack4/config_files/blob/master/hzn_genres.json\n'
    mapper.create_genre_warnings(hzn_genres_warnings_tmp, hzn_genres_warnings,
                                 provider, genre_pull)

    notify(addon_name,
           '{} {} {}'.format(loc(32370), provider, loc(32371)),
           icon=xbmcgui.NOTIFICATION_INFO)
    log('{} {} {}'.format(loc(32370), provider, loc(32371), xbmc.LOGNOTICE))

    if (os.path.isfile(hzn_channels_warnings)
            or os.path.isfile(hzn_genres_warnings)):
        notify(provider,
               '{}'.format(loc(32372)),
               icon=xbmcgui.NOTIFICATION_WARNING)

    ## Delete old Tempfiles, not needed any more
    for file in os.listdir(provider_temppath):
        xbmcvfs.delete(os.path.join(provider_temppath, file))
Ejemplo n.º 27
0
    def service(self, request, response):
        apiToken = request.getParam('apiToken')
        contentName = request.getParam('contentName')
        title = request.getParam('title')
        date = request.getParam('date')
        genre = request.getParam('genre')

        item = None
        if contentName is not None:
            try:
                dialog = xbmcgui.DialogProgressBG()
                dialog.create(self._(32007), self._(32008))
                videoContentUrl = Constants.apiBaseUrl + '/content/documents/' + contentName + '.json?profile=player'
                self.debug("downloading video-content-url '{1}' ...",
                           videoContentUrl)
                videoContent = VideoContentResource(videoContentUrl,
                                                    Constants.apiBaseUrl,
                                                    apiToken)
                self._parse(videoContent)

                if videoContent.streamInfoUrl is None:
                    self.warn(
                        "can't find stream-info-url in video-content '{1}' in content '{2}'",
                        contentName, videoContent.content)
                    response.sendError(
                        self._(32011) + " '" + contentName + "'",
                        Action('SearchPage'))
                    return

                dialog.update(percent=50, message=self._(32009))
                self.debug("downloading stream-info-url '{1}' ...",
                           videoContent.streamInfoUrl)
                streamInfo = StreamInfoResource(videoContent.streamInfoUrl,
                                                apiToken)
                self._parse(streamInfo)

                url = streamInfo.streamUrl
                if url is None:
                    self.warn(
                        "PlayVideo - can't find stream-url in stream-info-url '{1}' in content '{2}'",
                        videoContent.streamInfoUrl, streamInfo.content)
                    response.sendError(
                        self._(32012) + " '" + contentName + "'",
                        Action('SearchPage'))
                    return

                title = videoContent.title
                text = videoContent.text
                infoLabels = {}
                infoLabels['title'] = title
                infoLabels['sorttitle'] = title
                infoLabels['genre'] = genre
                #infoLabels['plot'] = text
                #infoLabels['plotoutline'] = text
                infoLabels['tvshowtitle'] = title
                infoLabels['tagline'] = text
                if videoContent.duration is not None:
                    infoLabels['duration'] = videoContent.duration
                infoLabels['mediatype'] = 'video'

                if date is not None and date != "":
                    infoLabels['date'] = date

                item = xbmcgui.ListItem(title, text)
                item.setPath(url)
                item.setInfo(type="Video", infoLabels=infoLabels)
                image = videoContent.image
                if image is not None:
                    item.setArt({
                        'poster': image,
                        'banner': image,
                        'thumb': image,
                        'icon': image,
                        'fanart': image
                    })

                # set subtitles
                self.setSubTitles(item, streamInfo.subTitlesUrl)

                dialog.update(percent=90, message=self._(32010))
                self.info("setting resolved url='{1}' ...", url)
                xbmcplugin.setResolvedUrl(response.handle, True, item)
            finally:
                dialog.close()
Ejemplo n.º 28
0
def doDownload(url, dest, title, image, folder, headers):
    def _hide_busy_dialog():
        if kodi_version >= 18: return xbmc.executebuiltin('Dialog.Close(busydialognocancel)')
        else: return xbmc.executebuiltin('Dialog.Close(busydialog)')
    kodi_version = int(xbmc.getInfoLabel("System.BuildVersion")[0:2])
    _addon__ = xbmcaddon.Addon(id='plugin.video.fen')
    headers = json.loads(unquote_plus(headers))
    url = unquote_plus(url)
    title = unquote_plus(title)
    image = unquote_plus(image)
    folder = unquote_plus(folder)
    dest = unquote_plus(dest)
    file = dest.rsplit(os.sep, 1)[-1]
    resp = getResponse(url, headers, 0)

    if not resp:
        _hide_busy_dialog()
        xbmcgui.Dialog().ok(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 resumable:
        print "Download is resumable"

    if content < 1:
        _hide_busy_dialog()
        xbmcgui.Dialog().ok(title, file, 'Unknown filesize', 'Unable to download')
        return

    size = 1024 * 1024
    mb   = content / (1024 * 1024)

    if content < size:
        size = content

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

    _hide_busy_dialog()

    if xbmcgui.Dialog().yesno('Fen' + ' - Confirm Download', '[B]%s[/B]' % title.upper(), 'Complete file is [B]%dMB[/B]' % mb, 'Continue with download?', 'Confirm',  'Cancel') == 1:
        return

    print 'Download File Size : %dMB %s ' % (mb, dest)

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

    f = xbmcvfs.File(dest, 'w')

    chunk  = None
    chunks = []

    show_notifications = True if _addon__.getSetting('download.notification') == '0' else False
    persistent_notifications = True if _addon__.getSetting('download.notification') == '2' else False
    suppress_during_playback = True if _addon__.getSetting('download.suppress') == 'true' else False
    try: notification_frequency = int(_addon__.getSetting('download.frequency'))
    except: notification_frequency = 10

    if persistent_notifications:
        progressDialog = xbmcgui.DialogProgressBG()
        progressDialog.create('Downloading [B]%s[/B]' % title, '')
        progressDialog.update(0, 'Commencing Download')

    while True:
        playing = xbmc.Player().isPlaying()
        downloaded = total
        for c in chunks:
            downloaded += len(c)
        percent = min(100 * downloaded / content, 100)

        if persistent_notifications:
            progressDialog.update(percent, 'Downloading [B]%s[/B]' % title, '')

        elif show_notifications:
            if percent >= notify:
                if playing and not suppress_during_playback:
                    xbmc.executebuiltin( "XBMC.Notification([B]%s[/B],[I]%s[/I],%i,%s)" % ('Download Progress: ' + str(percent)+'%', title, 10000, image))
                elif (not playing):
                    xbmc.executebuiltin( "XBMC.Notification([B]%s[/B],[I]%s[/I],%i,%s)" % ('Download Progress: ' + str(percent)+'%', title, 10000, image))

                notify += notification_frequency

        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()
                    try:
                        progressDialog.close()
                    except Exception:
                        pass
                    return done(title, True)

        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
            xbmc.sleep(sleep*1000)

        if (resumable and errors > 0) or errors >= 10:
            if (not resumable and resume >= 50) or resume >= 500:
                #Give up!
                try:
                    progressDialog.close()
                except Exception:
                    pass
                return done(title, False)

            resume += 1
            errors  = 0
            if resumable:
                chunks  = []
                #create new response
                resp = getResponse(url, headers, total)
            else:
                #use existing response
                pass
Ejemplo n.º 29
0
addonInfo = xbmcaddon.Addon().getAddonInfo

infoLabel = xbmc.getInfoLabel

condVisibility = xbmc.getCondVisibility

jsonrpc = xbmc.executeJSONRPC

window = xbmcgui.Window(10000)

dialog = xbmcgui.Dialog()

progressDialog = xbmcgui.DialogProgress()

progressDialogBG = xbmcgui.DialogProgressBG()

windowDialog = xbmcgui.WindowDialog()

button = xbmcgui.ControlButton

image = xbmcgui.ControlImage

keyboard = xbmc.Keyboard

sleep = xbmc.sleep

execute = xbmc.executebuiltin

skin = xbmc.getSkinDir()
Ejemplo n.º 30
0
def main():
    progress = xbmcgui.DialogProgressBG()
    try:
        progress.create("Watchdog starting. Please wait...")
    except:
        progress = None

    if settings.STARTUP_DELAY > 0:
        log("waiting for user delay of %d seconds" % settings.STARTUP_DELAY)
        msg = "Delaying startup by %d seconds."
        if progress:
            progress.update(0, message=msg % settings.STARTUP_DELAY)
        start = time.time()
        while time.time() - start < settings.STARTUP_DELAY:
            xbmc.sleep(100)
            if xbmc.abortRequested:
                if progress:
                    progress.close()
                return

    sources = []
    video_sources = settings.VIDEO_SOURCES
    sources.extend(zip(repeat('video'), video_sources))
    log("video sources %s" % video_sources)

    music_sources = settings.MUSIC_SOURCES
    sources.extend(zip(repeat('music'), music_sources))
    log("music sources %s" % music_sources)

    xbmcif = XBMCIF()
    if settings.CLEAN_ON_START:
        if video_sources:
            xbmcif.queue_clean('video')
        if music_sources:
            xbmcif.queue_clean('music')

    if settings.SCAN_ON_START:
        if video_sources:
            xbmcif.queue_scan('video')
        if music_sources:
            xbmcif.queue_scan('video')

    observer = MultiEmitterObserver()
    observer.start()  # start so emitters are started on schedule

    for i, (libtype, path) in enumerate(sources):
        if progress:
            progress.update((i + 1) / len(sources) * 100,
                            message="Setting up %s" % path)
        try:
            emitter_cls = emitters.select_emitter(path)
        except IOError:
            log("not watching <%s>. does not exist" % path)
            continue
        finally:
            if xbmc.abortRequested:
                break

        eh = EventHandler(libtype, path, xbmcif)
        try:
            observer.schedule(eh, path=path, emitter_cls=emitter_cls)
            log("watching <%s> using %s" % (path, emitter_cls))
        except Exception:
            traceback.print_exc()
            log("failed to watch <%s>" % path)
        finally:
            if xbmc.abortRequested:
                break

    xbmcif.start()
    if progress:
        progress.close()
    log("initialization done")

    if settings.SHOW_STATUS_DIALOG:
        watching = [
            "Watching '%s'" % path for _, path in sources
            if path in observer.paths
        ]
        not_watching = [
            "Not watching '%s'" % path for _, path in sources
            if path not in observer.paths
        ]
        dialog = xbmcgui.Dialog()
        try:
            dialog.select('Watchdog status', watching + not_watching)
        except:
            dialog = None

    if xbmc.__version__ >= '2.19.0':
        monitor = xbmc.Monitor()
        monitor.waitForAbort()
    else:
        while not xbmc.abortRequested:
            xbmc.sleep(100)

    log("stopping..")
    observer.stop()
    xbmcif.stop()
    observer.join()
    xbmcif.join()