Python xbmc.convertLanguage() Examples

The following are 6 code examples of xbmc.convertLanguage(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xbmc , or try the search function .
Example #1
Source File: website.py    From plugin.video.netflix with MIT License 5 votes vote down vote up
def parse_profiles(data):
    """Parse profile information from Netflix response"""
    profiles_list = jgraph_get_list('profilesList', data)
    try:
        if not profiles_list:
            raise InvalidProfilesError('It has not been possible to obtain the list of profiles.')
        sort_order = 0
        current_guids = []
        for index, profile_data in iteritems(profiles_list):  # pylint: disable=unused-variable
            summary = jgraph_get('summary', profile_data)
            guid = summary['guid']
            current_guids.append(guid)
            common.debug('Parsing profile {}', summary['guid'])
            avatar_url = _get_avatar(profile_data, data, guid)
            is_active = summary.pop('isActive')
            g.LOCAL_DB.set_profile(guid, is_active, sort_order)
            g.SHARED_DB.set_profile(guid, sort_order)
            # Add profile language description translated from locale
            summary['language_desc'] = g.py2_decode(xbmc.convertLanguage(summary['language'][:2], xbmc.ENGLISH_NAME))
            for key, value in iteritems(summary):
                if key in PROFILE_DEBUG_INFO:
                    common.debug('Profile info {}', {key: value})
                if key == 'profileName':  # The profile name is coded as HTML
                    value = parse_html(value)
                g.LOCAL_DB.set_profile_config(key, value, guid)
            g.LOCAL_DB.set_profile_config('avatar', avatar_url, guid)
            sort_order += 1
        _delete_non_existing_profiles(current_guids)
    except Exception:
        import traceback
        common.error(g.py2_decode(traceback.format_exc(), 'latin-1'))
        common.error('Profile list data: {}', profiles_list)
        raise InvalidProfilesError 
Example #2
Source File: kodiops.py    From plugin.video.netflix with MIT License 5 votes vote down vote up
def convert_language_iso(from_value, iso_format=xbmc.ISO_639_1, use_fallback=True):
    """
    Convert language code from an English name or three letter code (ISO 639-2) to two letter code (ISO 639-1)

    :param iso_format: specify the iso format (ISO_639_1 or ISO_639_2)
    :param use_fallback: if True when the conversion fails, is returned the current Kodi active language
    """
    converted_lang = xbmc.convertLanguage(g.py2_encode(from_value), iso_format)
    if not use_fallback:
        return converted_lang
    converted_lang = converted_lang if converted_lang else xbmc.getLanguage(iso_format, False)  # Get lang. active
    return converted_lang if converted_lang else 'en' if iso_format == xbmc.ISO_639_1 else 'eng' 
Example #3
Source File: pykodi.py    From script.artwork.beef with MIT License 5 votes vote down vote up
def get_language(language_format=xbmc.ENGLISH_NAME, region=False):
    language = xbmc.getLanguage(language_format, region)
    if not language or region and language.startswith('-'):
        engname = xbmc.getLanguage(xbmc.ENGLISH_NAME)
        regiontag = language
        if ' (' in engname:
            language = engname[:engname.rfind(' (')]
        if language_format != xbmc.ENGLISH_NAME:
            language = xbmc.convertLanguage(language, language_format) + regiontag
    return language 
Example #4
Source File: rpc.py    From addon with GNU General Public License v3.0 5 votes vote down vote up
def ConvertLanguage(self, *args, **kwargs):
        return xbmc.convertLanguage(*args, **kwargs) 
Example #5
Source File: artworkselection.py    From script.artwork.beef with MIT License 4 votes vote down vote up
def onInit(self):
        self.getControl(1).setLabel("Artwork Beef: " + L(CHOOSE_ART_HEADER).format(self.arttype, self.medialabel))
        self.getControl(3).setVisible(False)
        self.getControl(5).setVisible(self.multi)
        self.getControl(5).setLabel('$LOCALIZE[186]')
        self.guilist = self.getControl(6)

        for image in self.artlist:
            provider = image['provider'].display
            if isinstance(provider, int):
                provider = L(provider)
            secondprovider = image.get('second provider')
            if secondprovider:
                if isinstance(secondprovider, int):
                    secondprovider = L(secondprovider)
                provider = '{0}, {1}'.format(provider, secondprovider)
            title = image.get('title')
            if not title and 'subtype' in image:
                title = image['subtype'].display
            language = xbmc.convertLanguage(image['language'], xbmc.ENGLISH_NAME) if image.get('language') else None
            if not title:
                title = language
            if title and len(title) < 20 and not secondprovider:
                label = '{0} from {1}'.format(title, provider)
                summary = language if language and language != title else ''
            else:
                label = provider
                if language and language != title:
                    title = language + ' ' + title
                summary = title if title else ''
            rating = image.get('rating')
            size = image.get('size')
            if (rating or size) and summary:
                summary += '\n'
            if size:
                summary += image['size'].display
            if rating and size:
                summary += '   '
            if rating:
                summary += image['rating'].display
            listitem = xbmcgui.ListItem(label)
            listitem.setLabel2(summary)
            # DEPRECATED: Above Krypton and higher (only), below Jarvis and lower (only)
            listitem.setProperty('Addon.Summary', summary)
            listitem.setIconImage(image['preview'])
            # DEPRECATED: Above is deprecated in Jarvis, but still works through Krypton (at least)
            # listitem.setArt({'icon': image['preview']})
            listitem.setPath(image['url'])
            if image.get('existing'):
                listitem.select(True)
            self.guilist.addItem(listitem)
        self.setFocus(self.guilist) 
Example #6
Source File: proxy.py    From xbmc with GNU General Public License v3.0 4 votes vote down vote up
def _AlterGPR(self, endpoint, headers, data):
        """ GPR data alteration for better language parsing and subtitles streaming instead of pre-caching """

        try:
            from urllib.parse import quote_plus
        except ImportError:
            from urllib import quote_plus
        import json
        from xbmc import convertLanguage, ENGLISH_NAME

        status_code, headers, content = self._ForwardRequest('get', endpoint, headers, data)

        # Grab the subtitle urls, merge them in a single list, append the locale codes to let Kodi figure
        # out which URL has which language, then sort them neatly in a human digestible order.
        content = json.loads(content)
        content['subtitles'] = []
        newsubs = []

        # Count the number of duplicates with the same ISO 639-1 codes
        langCount = {'forcedNarratives': {}, 'subtitleUrls': {}}
        for sub_type in list(langCount):  # list() instead of .keys() to avoid py3 iteration errors
            if sub_type in content:
                for i in range(0, len(content[sub_type])):
                    lang = content[sub_type][i]['languageCode'][0:2]
                    if lang not in langCount[sub_type]:
                        langCount[sub_type][lang] = 0
                    langCount[sub_type][lang] += 1

        # Merge the different subtitles lists in a single one, and append a spurious name file
        # to let Kodi figure out the locale, while at the same time enabling subtitles to be
        # proxied and transcoded on-the-fly.
        for sub_type in list(langCount):  # list() instead of .keys() to avoid py3 iteration errors
            if sub_type in content:
                for i in range(0, len(content[sub_type])):
                    fn = self._AdjustLocale(content[sub_type][i]['languageCode'], langCount[sub_type][content[sub_type][i]['languageCode'][0:2]])
                    variants = '{}{}'.format(
                        '-[CC]' if 'sdh' == content[sub_type][i]['type'] else '',
                        '.Forced' if 'forcedNarratives' == sub_type else ''
                    )
                    # Proxify the URLs, with a make believe Kodi-friendly file name
                    escapedurl = quote_plus(content[sub_type][i]['url'])
                    content[sub_type][i]['url'] = 'http://127.0.0.1:{}/subtitles/{}/{}{}.srt'.format(
                        self.server.port,
                        escapedurl,
                        fn,
                        variants
                    )
                    cl = py2_decode(convertLanguage(fn[0:2], ENGLISH_NAME))
                    newsubs.append((content[sub_type][i], cl, fn, variants, escapedurl))
                del content[sub_type]  # Reduce the data transfer by removing the lists we merged

        # Create the new merged subtitles list, and append time stretched variants.
        for sub in [x for x in sorted(newsubs, key=lambda sub: (sub[1], sub[2], sub[3]))]:
            content['subtitles'].append(sub[0])

        self._SendResponse(status_code, headers, json.dumps(content), True)