Example #1
0
def notify_all(encoding, method, data):
    next_data = json.dumps(data)
    if not isinstance(next_data, bytes):
        next_data = next_data.encode('utf-8')

    if encoding == 'base64':
        from base64 import b64encode  # pylint: disable=import-outside-toplevel
        data = b64encode(next_data)
        if PY3:
            data = data.decode('ascii')
    elif encoding == 'hex':
        from binascii import hexlify  # pylint: disable=import-outside-toplevel
        if PY3:
            if not isinstance(next_data, bytes):
                next_data = next_data.encode('utf-8')
            data = hexlify(next_data).decode('utf-8')
        else:
            data = hexlify(next_data)

    jsonrpc_request = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "JSONRPC.NotifyAll",
        "params": {
            "sender": "%s.SIGNAL" % CONFIG['id'],
            "message": method,
            "data": [data],
        }
    }

    xbmc.executeJSONRPC(json.dumps(jsonrpc_request))
def playAt(path, h=0, m=0, s=0, ms=0):
    """
    Plays the video specified by path.
    Optionally set the start position with h,m,s,ms keyword args.
    """
    xbmc.executeJSONRPC(
        '{"jsonrpc": "2.0", "method": "Player.Open", "params": {"item":{"file":"%s"},"options":{"resume":{"hours":%s,"minutes":%s,"seconds":%s,"milliseconds":%s}}}, "id": 1}'
        % (path, h, m, s, ms)  # noqa 501
    )
Example #3
0
 def executeCommand(self):
     jsonCommand = {
         'jsonrpc': '2.0',
         'method': self.command['method'],
         'params': self.command['params'],
         'id': 44
     }
     utils.log(json.dumps(jsonCommand))
     xbmc.executeJSONRPC(json.dumps(jsonCommand))
Example #4
0
 def disable(self, build):
     xbmcgui.Dialog().notification(ADDON_NAME, VERSION, ICON, 8000)
     if not xbmcgui.Dialog().yesno(ADDON_NAME,
                                   LANGUAGE(30011) %
                                   (build), LANGUAGE(30012)):
         return False
     xbmc.executeJSONRPC(
         '{"jsonrpc": "2.0", "method":"Addons.SetAddonEnabled","params":{"addonid":"%s","enabled":false}, "id": 1}'
         % (ADDON_ID))
     xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30009), ICON, 4000)
     return False
Example #5
0
def jsonrpc_play(url):
    jsonrpc_request = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "player.open",
        "params": {
            "item": {
                "file": url
            }
        }
    }

    xbmc.executeJSONRPC(json.dumps(jsonrpc_request))
Example #6
0
def start():
    restart_queued = False

    while not monitor.waitForAbort(2):
        forced = ADDON_DEV or xbmc.getInfoLabel(
            'Skin.String({})'.format(ADDON_ID)) == FORCE_RUN_FLAG

        if forced or (settings.getBool('auto_merge', True)
                      and time.time() - userdata.get('last_run', 0) >
                      settings.getInt('reload_time_mins', 10) * 60):
            xbmc.executebuiltin('Skin.SetString({},{})'.format(
                ADDON_ID, FORCE_RUN_FLAG))

            try:
                run_merge([Source.PLAYLIST, Source.EPG])
            except Exception as e:
                result = False
                log.exception(e)
            else:
                result = True

            userdata.set('last_run', int(time.time()))
            xbmc.executebuiltin('Skin.SetString({},)'.format(ADDON_ID))

            if result:
                restart_queued = True

                if forced:
                    gui.notification(_.MERGE_COMPLETE)

            elif forced:
                gui.exception()

        if restart_queued and (
                forced or
            (settings.getBool('restart_pvr', False)
             and not xbmc.getCondVisibility('Pvr.IsPlayingTv')
             and not xbmc.getCondVisibility('Pvr.IsPlayingRadio'))):
            restart_queued = False

            xbmc.executeJSONRPC(
                '{{"jsonrpc":"2.0","id":1,"method":"Addons.SetAddonEnabled","params":{{"addonid":"{}","enabled":false}}}}'
                .format(IPTV_SIMPLE_ID))
            monitor.waitForAbort(2)
            xbmc.executeJSONRPC(
                '{{"jsonrpc":"2.0","id":1,"method":"Addons.SetAddonEnabled","params":{{"addonid":"{}","enabled":true}}}}'
                .format(IPTV_SIMPLE_ID))

        if ADDON_DEV:
            break
Example #7
0
    def _json_rpc_request(payload):
        """Kodi JSON-RPC request. Return the response in a dictionary."""
        log('jsonrpc payload: {payload}', payload=payload)
        response = xbmc.executeJSONRPC(json.dumps(payload))
        log('jsonrpc response: {response}', response=response)

        return json.loads(response)
 def addon_status(self, addon_id):
     request = {
         "jsonrpc": "2.0",
         "method": "Addons.GetAddonDetails",
         "id": 1,
         "params": {
             "addonid": "%s" % addon_id,
             "properties": ["enabled"]
         }
     }
     response = xbmc.executeJSONRPC(json.dumps(request))
     response = json.loads(response)
     try:
         is_enabled = response['result']['addon']['enabled'] is True
         xbmc.log(
             self.addon_name + '.settings -> %s is %s' %
             (addon_id, 'enabled' if is_enabled else 'disabled'),
             xbmc.LOGDEBUG)
         return is_enabled
     except KeyError:
         xbmc.log(
             self.addon_name +
             '.settings -> addon_status received an unexpected response',
             xbmc.LOGERROR)
         return False
Example #9
0
 def send(self, sender, message, data):
     params = {"message": message, "sender": sender, "data": data}
     error = json.loads(
         xbmc.executeJSONRPC(
             json.dumps(dict(self.__request__,
                             params=params)))).get("error")
     if error:
         raise JSONRPCError(error)
Example #10
0
def _reset(**kwargs):
    if not gui.yes_no(_.PLUGIN_RESET_YES_NO):
        return

    _close()

    try:
        xbmc.executeJSONRPC('{{"jsonrpc":"2.0","id":1,"method":"Addons.SetAddonEnabled","params":{{"addonid":"{}","enabled":false}}}}'.format(ADDON_ID))
        shutil.rmtree(ADDON_PROFILE)
    except:
        pass
        
    xbmc.executeJSONRPC('{{"jsonrpc":"2.0","id":1,"method":"Addons.SetAddonEnabled","params":{{"addonid":"{}","enabled":true}}}}'.format(ADDON_ID))

    gui.notification(_.PLUGIN_RESET_OK)
    signals.emit(signals.AFTER_RESET)
    gui.refresh()
Example #11
0
 def getUPNP(self):
     log('getUPNP')
     """ Check Kodi UPNP support. """
     json_query = ('{"jsonrpc":"2.0","method":"Settings.GetSettingValue","params":{"setting":"services.upnp"},"id":1}')
     data = json.loads(xbmc.executeJSONRPC(json_query))
     try:
         if 'result' in data and 'value' in data['result']: return data['result']['value']
     except Exception as e: log('getUPNP, Failed! ' + str(e))
     return False
Example #12
0
def okDisable(msg):
    if yesnoDialog(msg, nolabel=LANGUAGE(30009), yeslabel=LANGUAGE(30015)):
        results = xbmc.executeJSONRPC(
            '{"jsonrpc": "2.0", "method":"Addons.SetAddonEnabled", "params":{"addonid":"%s","enabled":false}, "id": 1}'
            % ADDON_ID)
        if results and "OK" in results:
            return notificationDialog(LANGUAGE(30016))
    else:
        sys.exit()
Example #13
0
 def _auto_switch_stream(self):
     if self.SETTINGS['codec_delay'] > 0:
         self.LW.log([
             'waiting %s seconds before trying to get stream details' %
             str(self.SETTINGS['codec_delay'])
         ])
         self.waitForAbort(self.SETTINGS['codec_delay'])
     response = xbmc.executeJSONRPC(
         '{"jsonrpc":"2.0", "method":"Player.GetProperties", "params":{"playerid":1, "properties":["currentaudiostream"]}, "id":1}'
     )
     r_dict = json.loads(response)
     self.LW.log(['got back audio stream data of:', r_dict])
     try:
         codec = r_dict['result']['currentaudiostream']['codec']
     except (IndexError, KeyError, ValueError, TypeError):
         codec = None
     try:
         channels = r_dict['result']['currentaudiostream']['channels']
     except (IndexError, KeyError, ValueError, TypeError):
         channels = None
     self.LW.log([
         'got %s for the codec and %s for the channels' %
         (str(codec), str(channels))
     ])
     if codec:
         codec_set = 'auto_othercodec'
         for check_codec in ['ac3', 'eac3', 'dts', 'dtshd', 'truehd']:
             if codec in check_codec:
                 codec_set = 'auto_%s' % check_codec
                 break
     else:
         codec_set = 'none'
     try:
         codec_setting = self.SETTINGS[codec_set]
     except KeyError:
         codec_setting = '0'
     if channels:
         if channels > 2:
             channels_set = 'auto_multichannel'
         else:
             channels_set = 'auto_stereo'
     else:
         channels_set = 'none'
     try:
         channels_setting = self.SETTINGS[channels_set]
     except KeyError:
         channels_setting = '0'
     self.LW.log([
         'got codec set of %s and channels set of %s' %
         (codec_set, channels_set)
     ])
     self.LW.log([
         'sending back codec setting of %s and channel setting of %s' %
         (codec_setting, channels_setting)
     ])
     return codec_setting, channels_setting
Example #14
0
 def getUPNP_ID(self):
     log('getUPNP_ID')
     """ Check if upnp id is valid. """
     json_query = ('{"jsonrpc":"2.0","method":"Files.GetDirectory","params":{"directory":"%s"},"id":1}'%BASE_UPNP)
     try:
         if not json.loads(xbmc.executeJSONRPC(json_query))['result']['files'][0]['file'].endswith('/playonprovider/'): return None
     except Exception as e: 
         log('getUPNP_ID, Failed! ' + str(e))
         return None
     return BASE_UPNP
Example #15
0
def get_KodiVersion():
    json_query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Application.GetProperties", "params": {"properties": ["version", "name"]}, "id": 1 }')
    if sys.version_info[0] >= 3:
        json_query = str(json_query)
    else:
        json_query = json_query.encode('utf-8')
    json_query = json.loads(json_query)
    version_installed = []
    if 'result' in json_query and 'version' in json_query['result']:
        version_installed  = json_query['result']['version']
    return version_installed
Example #16
0
def get_gui_settings(keys):
    settings = {}

    for key in keys:
        try:
            value = json.loads(xbmc.executeJSONRPC('{{"jsonrpc":"2.0", "method":"Settings.GetSettingValue", "params":{{"setting":"{}"}}, "id":1}}'.format(key)))['result']['value']
            settings[key] = value
        except:
            pass
        
    return settings
Example #17
0
 def sendJSON(self, command, life=datetime.timedelta(seconds=60)):
     log('sendJSON, command = ' + (command))
     cacheresponse = self.cache.get(ADDON_NAME +
                                    '.sendJSON, command = %s' % command)
     if DEBUG: cacheresponse = None
     if not cacheresponse:
         cacheresponse = xbmc.executeJSONRPC(command)
         self.cache.set(ADDON_NAME + '.sendJSON, command = %s' % command,
                        cacheresponse,
                        expiration=life)
     return loadJSON(cacheresponse)
Example #18
0
def send_json_rpc(method, params=None):
    # type: (Text, Optional[Dict[Text, Any]]) -> dict
    """
    Send JSON-RPC to Kodi
    """
    request = {'jsonrpc': '2.0', 'method': method, 'id': '1'}
    if params is not None:
        request['params'] = params
    logger.debug('JSON-RPC request:\n{0}'.format(pformat(request)))
    json_reply = json.loads(xbmc.executeJSONRPC(json.dumps(request)))
    logger.debug('JSON-RPC reply:\n{0}'.format(pformat(json_reply)))
    return json_reply['result']
Example #19
0
 def _profile(self, profile):
     loglines, result = readFile( os.path.join( self.SETTINGS['ADDONDATAPATH'], 'profile%s.json' % profile ) )
     self.LW.log( loglines )
     try:
         jsonResult = json.loads( result )
     except ValueError:
         self._notification( '%s %s (%s)' % (self.SETTINGS['ADDONLANGUAGE']( 32104 ), profile, self.SNAME[int( profile )]),
                            self.SETTINGS['notify_maintenance'] )
         self.LW.log( ['LOAD JSON FROM FILE: Error reading from profile - %s' % str( profile )], xbmc.LOGERROR )
         return False
     quote_needed = ['audiooutput.audiodevice',
                     'audiooutput.passthroughdevice',
                     'locale.audiolanguage',
                     'lookandfeel.soundskin']
     self.LW.log( ['RESTORING SETTING: %s' % self.SNAME[int( profile )]], xbmc.LOGINFO )
     for set_name, set_value in jsonResult.items():
         if not self.SETTINGS['player'] and set_name.startswith('videoplayer'):
             continue
         if not self.SETTINGS['video'] and set_name.startswith('videoscreen'):
             continue
         self.LW.log( ['RESTORING SETTING: %s: %s' % (set_name, set_value)] )
         if set_name in quote_needed:
             set_value = '"%s"' % set_value
         if self.SETTINGS['volume'] and set_name == 'volume':
             xbmc.executeJSONRPC(
                 '{"jsonrpc": "2.0", "method": "Application.SetVolume", "params": {"volume": %s}, "id": 1}' % jsonResult['volume'] )
         else:
             xbmc.executeJSONRPC(
                 '{"jsonrpc": "2.0", "method": "Settings.SetSettingValue", "params": {"setting": "%s", "value": %s}, "id": 1}' % (set_name, set_value) )
     if self.AUTO:
         show_notification = self.SETTINGS['notify_auto']
     else:
         show_notification = self.SETTINGS['notify_manual']
     self._notification( self.SNAME[int( profile )], show_notification )
     success, loglines = writeFile( profile, os.path.join(self.SETTINGS['ADDONDATAPATH'], 'profile'), 'w' )
     self.LW.log( loglines )
     s_cec = self.SETTINGS['profile%s_cec' % profile]
     if s_cec:
         self.LW.log( ['SENDING CEC COMMAND: %s' % self.CECCOMMANDS[s_cec]], xbmc.LOGINFO )
         xbmc.executebuiltin(self.CECCOMMANDS[s_cec])
Example #20
0
def get_now_played():
    """
    Get info about the currently played file via JSON-RPC.
    Alternatively this can be done via Kodi InfoLabels.

    :return: currently played item's data
    :rtype: dict
    """
    request = json.dumps(
        {'jsonrpc': '2.0',
         'method': 'Player.GetItem',
         'params': {
             'playerid': 1,
             'properties': ['file', 'showtitle', 'season', 'episode']
         },
         'id': '1'}
    )
    return json.loads(xbmc.executeJSONRPC(request))['result']['item']
Example #21
0
 def send(cls, request):
     if not request:
         raise exception.MissingParameter('equest')
     return JsonResponse(xbmc.executeJSONRPC(request.to_json()))
Example #22
0
def executeJSONRPC(json):
    return xbmc.executeJSONRPC(json)