Exemplo n.º 1
0
def _get_error_details(decoded_response):
    # Catch a chunk error
    if 'errordata' in decoded_response:
        return g.py2_encode(json.loads(base64.standard_b64decode(decoded_response['errordata']))['errormsg'])
    # Catch a manifest error
    if 'error' in decoded_response:
        if decoded_response['error'].get('errorDisplayMessage'):
            return g.py2_encode(decoded_response['error']['errorDisplayMessage'])
    # Catch a license error
    if 'result' in decoded_response and isinstance(decoded_response.get('result'), list):
        if 'error' in decoded_response['result'][0]:
            if decoded_response['result'][0]['error'].get('errorDisplayMessage'):
                return g.py2_encode(decoded_response['result'][0]['error']['errorDisplayMessage'])
    return g.py2_encode('Unhandled error check log.')
Exemplo n.º 2
0
def run(argv):
    # pylint: disable=broad-except,ungrouped-imports
    # Initialize globals right away to avoid stale values from the last addon invocation.
    # Otherwise Kodi's reuseLanguageInvoker will cause some really quirky behavior!
    # PR: https://github.com/xbmc/xbmc/pull/13814
    g.init_globals(argv)

    reset_log_level_global_var()
    info('Started (Version {})'.format(g.VERSION_RAW))
    info('URL is {}'.format(g.URL))
    success = True

    window_cls = Window(10000)  # Kodi home window

    # If you use multiple Kodi profiles you need to distinguish the property of current profile
    prop_nf_service_status = g.py2_encode('nf_service_status_' +
                                          get_current_kodi_profile_name())
    is_external_call = _check_addon_external_call(window_cls,
                                                  prop_nf_service_status)
    service_status = _get_service_status(window_cls, prop_nf_service_status)

    if service_status.get('status') != 'running':
        if not is_external_call:
            if service_status.get('status') == 'error':
                # The services are not started due to an error exception
                from resources.lib.kodi.ui import show_error_info
                show_error_info(
                    get_local_string(30105),
                    get_local_string(30240).format(
                        service_status.get('message')), False, False)
            else:
                # The services are not started yet
                from resources.lib.kodi.ui import show_backend_not_ready
                show_backend_not_ready()
        success = False

    if success:
        try:
            if _check_valid_credentials():
                if g.IS_ADDON_FIRSTRUN:
                    if check_addon_upgrade():
                        from resources.lib.config_wizard import run_addon_configuration
                        run_addon_configuration()
                route([part for part in g.PATH.split('/') if part])
            else:
                success = False
        except BackendNotReady:
            from resources.lib.kodi.ui import show_backend_not_ready
            show_backend_not_ready()
            success = False
        except Exception as exc:
            import traceback
            from resources.lib.kodi.ui import show_addon_error_info
            error(g.py2_decode(traceback.format_exc(), 'latin-1'))
            show_addon_error_info(exc)
            success = False

    if not success:
        _handle_endofdirectory()
    log_time_trace()
Exemplo n.º 3
0
def _log(msg, level, *args, **kwargs):
    """Log a message to the Kodi logfile."""
    if args or kwargs:
        msg = msg.format(*args, **kwargs)
    xbmc.log(
        g.py2_encode('[{identifier} ({handle})] {msg}'.format(
            identifier=g.ADDON_ID, handle=g.PLUGIN_HANDLE, msg=msg)), level)
Exemplo n.º 4
0
def make_http_call(callname, data):
    """Make an IPC call via HTTP and wait for it to return.
    The contents of data will be expanded to kwargs and passed into the target function."""
    from collections import OrderedDict
    try:  # Python 3
        from urllib.request import build_opener, install_opener, ProxyHandler, HTTPError, URLError, urlopen
    except ImportError:  # Python 2
        from urllib2 import build_opener, install_opener, ProxyHandler, HTTPError, URLError, urlopen
    import json
    debug('Handling HTTP IPC call to {}'.format(callname))
    # Note: On python 3, using 'localhost' slowdown the call (Windows OS is affected) not sure if it is an urllib issue
    url = 'http://127.0.0.1:{}/{}'.format(
        g.LOCAL_DB.get_value('ns_service_port', 8001), callname)
    install_opener(build_opener(ProxyHandler(
        {})))  # don't use proxy for localhost
    try:
        result = json.loads(urlopen(url=url,
                                    data=json.dumps(data).encode('utf-8'),
                                    timeout=IPC_TIMEOUT_SECS).read(),
                            object_pairs_hook=OrderedDict)
    except HTTPError as exc:
        result = json.loads(exc.reason)
    except URLError as exc:
        # On PY2 the exception message have to be decoded with latin-1 for system with symbolic characters
        err_msg = g.py2_decode(str(exc), 'latin-1')
        if '10049' in err_msg:
            err_msg += '\r\nPossible cause is wrong localhost settings in your operative system.'
        error(err_msg)
        raise BackendNotReady(g.py2_encode(err_msg, encoding='latin-1'))
    _raise_for_error(callname, result)
    return result
Exemplo n.º 5
0
def make_http_call_cache(callname, params, data):
    """Make an IPC call via HTTP and wait for it to return.
    The contents of data will be expanded to kwargs and passed into the target function."""
    try:  # Python 3
        from urllib.request import build_opener, install_opener, ProxyHandler, HTTPError, URLError, Request, urlopen
    except ImportError:  # Python 2
        from urllib2 import build_opener, install_opener, ProxyHandler, HTTPError, URLError, Request, urlopen
    import json
    # debug('Handling HTTP IPC call to {}'.format(callname))
    # Note: On python 3, using 'localhost' slowdown the call (Windows OS is affected) not sure if it is an urllib issue
    url = 'http://127.0.0.1:{}/{}'.format(
        g.LOCAL_DB.get_value('cache_service_port', 8002), callname)
    install_opener(build_opener(ProxyHandler(
        {})))  # don't use proxy for localhost
    r = Request(url=url, data=data, headers={'Params': json.dumps(params)})
    try:
        result = urlopen(r, timeout=IPC_TIMEOUT_SECS).read()
    except HTTPError as exc:
        try:
            raise apierrors.__dict__[exc.reason]()
        except KeyError:
            raise Exception('The service has returned: {}'.format(exc.reason))
    except URLError as exc:
        # On PY2 the exception message have to be decoded with latin-1 for system with symbolic characters
        err_msg = g.py2_decode(str(exc), 'latin-1')
        if '10049' in err_msg:
            err_msg += '\r\nPossible cause is wrong localhost settings in your operative system.'
        error(err_msg)
        raise BackendNotReady(g.py2_encode(err_msg, encoding='latin-1'))
    return result
Exemplo n.º 6
0
 def __init__(self):
     self.window_cls = Window(10000)  # Kodi home window
     # If you use multiple Kodi profiles you need to distinguish the property of current profile
     self.prop_nf_service_status = g.py2_encode(
         'nf_service_status_' + get_current_kodi_profile_name())
     self.controller = None
     self.library_updater = None
     self.settings_monitor = None
Exemplo n.º 7
0
def get_kodi_audio_language():
    """
    Return the audio language from Kodi settings
    """
    audio_language = json_rpc('Settings.GetSettingValue',
                              {'setting': 'locale.audiolanguage'})
    audio_language = xbmc.convertLanguage(
        g.py2_encode(audio_language['value']), xbmc.ISO_639_1)
    audio_language = audio_language if audio_language else xbmc.getLanguage(
        xbmc.ISO_639_1, False)
    return audio_language if audio_language else 'en'
Exemplo n.º 8
0
def convert_language_iso(from_value, 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 use_fallback: if True when the conversion fails, is returned the current Kodi active language
    """
    converted_lang = xbmc.convertLanguage(g.py2_encode(from_value), xbmc.ISO_639_1)
    if not use_fallback:
        return converted_lang
    converted_lang = converted_lang if converted_lang else xbmc.getLanguage(xbmc.ISO_639_1, False)
    return converted_lang if converted_lang else 'en'
Exemplo n.º 9
0
def run(argv):
    # pylint: disable=broad-except,ungrouped-imports
    # Initialize globals right away to avoid stale values from the last addon invocation.
    # Otherwise Kodi's reuseLanguageInvoker will cause some really quirky behavior!
    # PR: https://github.com/xbmc/xbmc/pull/13814
    g.init_globals(argv)

    reset_log_level_global_var()
    info('Started (Version {})'.format(g.VERSION))
    info('URL is {}'.format(g.URL))
    success = True

    window_cls = Window(10000)  # Kodi home window

    # If you use multiple Kodi profiles you need to distinguish the property of current profile
    prop_nf_service_status = g.py2_encode('nf_service_status_' +
                                          get_current_kodi_profile_name())
    is_widget_skin_call = _skin_widget_call(window_cls, prop_nf_service_status)

    if window_cls.getProperty(prop_nf_service_status) != 'running':
        if not is_widget_skin_call:
            from resources.lib.kodi.ui import show_backend_not_ready
            show_backend_not_ready()
        success = False

    if success:
        try:
            if _check_valid_credentials():
                if g.IS_ADDON_FIRSTRUN:
                    check_addon_upgrade()
                g.initial_addon_configuration()
                if not is_widget_skin_call:
                    update_cache_videoid_runtime(window_cls)
                route([part for part in g.PATH.split('/') if part])
            else:
                success = False
        except BackendNotReady:
            from resources.lib.kodi.ui import show_backend_not_ready
            show_backend_not_ready()
            success = False
        except Exception as exc:
            import traceback
            from resources.lib.kodi.ui import show_addon_error_info
            error(traceback.format_exc())
            show_addon_error_info(exc)
            success = False

    if not success:
        _handle_endofdirectory()

    g.CACHE.commit()
    log_time_trace()
Exemplo n.º 10
0
def get_kodi_subtitle_language():
    """
    Return the subtitle language from Kodi settings
    """
    subtitle_language = json_rpc('Settings.GetSettingValue',
                                 {'setting': 'locale.subtitlelanguage'})
    if subtitle_language['value'] == 'forced_only':
        return subtitle_language['value']
    subtitle_language = xbmc.convertLanguage(
        g.py2_encode(subtitle_language['value']), xbmc.ISO_639_1)
    subtitle_language = subtitle_language if subtitle_language else xbmc.getLanguage(
        xbmc.ISO_639_1, False)
    subtitle_language = subtitle_language if subtitle_language else 'en'
    return subtitle_language
Exemplo n.º 11
0
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'
Exemplo n.º 12
0
def show_notification(msg, title='Netflix', time=3000):
    """Show a notification"""
    xbmc.executebuiltin(
        g.py2_encode('Notification({}, {}, {}, {})'.format(
            title, msg, time, g.ICON)))
Exemplo n.º 13
0
def _convert_season(value):
    if isinstance(value, int):
        return str(value)
    # isdigit is needed to filter out non numeric characters from 'shortName' key
    return ''.join([n for n in g.py2_encode(value) if n.isdigit()])
Exemplo n.º 14
0
 def _window_property(self, bucket):
     return g.py2_encode('nfmemcache_{}_{}'.format(self.properties_prefix,
                                                   bucket))
Exemplo n.º 15
0
def run(argv):
    # pylint: disable=broad-except,ungrouped-imports,too-many-branches
    # Initialize globals right away to avoid stale values from the last addon invocation.
    # Otherwise Kodi's reuseLanguageInvoker will cause some really quirky behavior!
    # PR: https://github.com/xbmc/xbmc/pull/13814
    g.init_globals(argv)

    reset_log_level_global_var()
    info('Started (Version {})'.format(g.VERSION_RAW))
    info('URL is {}'.format(g.URL))
    success = True

    window_cls = Window(10000)  # Kodi home window

    # If you use multiple Kodi profiles you need to distinguish the property of current profile
    prop_nf_service_status = g.py2_encode('nf_service_status_' +
                                          get_current_kodi_profile_name())
    is_external_call = _check_addon_external_call(window_cls,
                                                  prop_nf_service_status)
    service_status = _get_service_status(window_cls, prop_nf_service_status)

    if service_status.get('status') != 'running':
        if not is_external_call:
            if service_status.get('status') == 'error':
                # The services are not started due to an error exception
                from resources.lib.kodi.ui import show_error_info
                show_error_info(
                    get_local_string(30105),
                    get_local_string(30240).format(
                        service_status.get('message')), False, False)
            else:
                # The services are not started yet
                from resources.lib.kodi.ui import show_backend_not_ready
                show_backend_not_ready()
        success = False

    if success:
        try:
            if _check_valid_credentials():
                if g.IS_ADDON_FIRSTRUN:
                    if check_addon_upgrade():
                        from resources.lib.config_wizard import run_addon_configuration
                        run_addon_configuration()
                route([part for part in g.PATH.split('/') if part])
            else:
                success = False
        except BackendNotReady:
            from resources.lib.kodi.ui import show_backend_not_ready
            show_backend_not_ready()
            success = False
        except InputStreamHelperError as exc:
            from resources.lib.kodi.ui import show_ok_dialog
            show_ok_dialog('InputStream Helper Add-on error', (
                'The operation has been cancelled.\r\n'
                'InputStream Helper has generated an internal error:\r\n{}\r\n\r\n'
                'Please report it to InputStream Helper github.'.format(exc)))
            success = False
        except HttpError401:
            # Http error 401 Client Error: Unauthorized for url ... issue (see _request in nfsession_requests.py)
            from resources.lib.kodi.ui import show_ok_dialog
            show_ok_dialog(get_local_string(30105), (
                'There was a communication problem with Netflix.\r\n'
                'This is a known and unresolvable issue, do not submit reports.\r\n'
                'You can try the operation again or exit.'))
            success = False
        except Exception as exc:
            import traceback
            from resources.lib.kodi.ui import show_addon_error_info
            error(g.py2_decode(traceback.format_exc(), 'latin-1'))
            show_addon_error_info(exc)
            success = False

    if not success:
        _handle_endofdirectory()
    log_time_trace()
Exemplo n.º 16
0
def play_media(media):
    """Play a media in Kodi"""
    xbmc.executebuiltin(g.py2_encode('PlayMedia({})'.format(media)))