我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用xbmc.executeJSONRPC()。
def kodi_json_request(params): data = json.dumps(params) request = xbmc.executeJSONRPC(data) try: response = json.loads(request) except UnicodeDecodeError: response = json.loads(request.decode('utf-8', 'ignore')) try: if 'result' in response: return response['result'] return None except KeyError: log("[%s] %s" % (params['method'], response['error']['message']),level=xbmc.LOGWARNING) return None
def kodi_json(jsonmethod, params=None): '''get info from the kodi json api''' import json kodi_json = {} kodi_json["jsonrpc"] = "2.0" kodi_json["method"] = jsonmethod if not params: params = {} kodi_json["params"] = params kodi_json["id"] = 1 json_response = xbmc.executeJSONRPC(json.dumps(kodi_json).encode("utf-8")) json_object = json.loads(json_response.decode('utf-8', 'replace')) result = None if 'result' in json_object: # look for correct returntype if isinstance(json_object['result'], dict): for key, value in json_object['result'].iteritems(): if not key == "limits": result = value break else: return json_object['result'] return result
def JSONRPC(method, params={}): """ Execute JSON-RPC method :param method: name of the method. Example "Input.Back" :type method: str :param params: dictionary with parameter values :type params: dict :return: response as a string or None (in case of exception) :rtype: str or None """ data = { "jsonrpc": "2.0", "id": 1, "method": method, "params": params } command = json.dumps(data) try: response = xbmc.executeJSONRPC(command) except Exception, e: log_exception("Error executing JSON RPC method " + method) log_exception("Params: " + str(params)) log_exception(str(e)) return None return response
def get_kodi_version(cls): """ Retrieves the Kodi version (Defaults to 17) :returns: string - Kodi version """ version = 17 payload = { 'jsonrpc': '2.0', 'method': 'Application.GetProperties', 'params': { 'properties': ['version', 'name'] }, 'id': 1 } response = xbmc.executeJSONRPC(json.dumps(payload)) responses_uni = unicode(response, 'utf-8', errors='ignore') response_serialized = json.loads(responses_uni) if 'error' not in response_serialized.keys(): result = response_serialized.get('result', {}) version_raw = result.get('version', {}) version = version_raw.get('major', 17) return version
def get_inputstream_version(cls): """ Retrieves the Inputsteam version (Defaults to 1.0.0) :returns: string - Inputsteam version """ payload = { 'jsonrpc': '2.0', 'id': 1, 'method': 'Addons.GetAddonDetails', 'params': { 'addonid': 'inputstream.adaptive', 'properties': ['enabled', 'version'] } } # execute the request response = xbmc.executeJSONRPC(json.dumps(payload)) responses_uni = unicode(response, 'utf-8', errors='ignore') response_serialized = json.loads(responses_uni) if 'error' not in response_serialized.keys(): result = response_serialized.get('result', {}) addon = result.get('addon', {}) if addon.get('enabled', False) is True: return addon.get('version', '1.0.0') return '1.0.0'
def get_inputstream_addon(): """Checks if the inputstream addon is installed & enabled. Returns the type of the inputstream addon used and if it's enabled, or None if not found. Returns ------- :obj:`tuple` of obj:`str` and bool, or None Inputstream addon and if it's enabled, or None """ type = 'inputstream.adaptive' payload = { 'jsonrpc': '2.0', 'id': 1, 'method': 'Addons.GetAddonDetails', 'params': { 'addonid': type, 'properties': ['enabled'] } } response = xbmc.executeJSONRPC(json.dumps(payload)) data = json.loads(response) if 'error' not in data.keys(): return type, data['result']['addon']['enabled'] return None, None
def kodi_json_request(params): data = json.dumps(params) request = xbmc.executeJSONRPC(data) try: response = json.loads(request) except UnicodeDecodeError: response = json.loads(request.decode('utf-8', 'ignore')) try: if 'result' in response: return response['result'] return None except KeyError: logger.warn("[%s] %s" % (params['method'], response['error']['message'])) return None
def get_details_from_player(): """Docstring""" logging.debug("addictedutils.get_details_from_player() begin") # Create request request = { "jsonrpc": "2.0", "method": "Player.GetItem", "params": { "properties": [ "showtitle", "season", "episode", "duration", "file"], "playerid": 1 }, "id": "VideoGetItem" } # Make request response = xbmc.executeJSONRPC(json.dumps(request)) logging.debug("response: " + pretty_json(response)) parsed_response = json.loads(response)['result']['item'] logging.debug("parsed_response: " + json.dumps(parsed_response, indent=2, sort_keys=True)) return parsed_response
def get_details_from_player(): # Create request request = { "jsonrpc": "2.0", "method": "Player.GetItem", "params": { "properties": ["showtitle", "season", "episode", "duration", "file"], "playerid": 1 }, "id": "VideoGetItem" } # Make request response = xbmc.executeJSONRPC(json.dumps(request)) print(response) parsed_response = json.loads(response)['result']['item'] print("---------") print(parsed_response) print("---------") return parsed_response
def channel_to_favs(channel_name, channel_id): params = { 'action': 'play_channel', 'channel_id': channel_id, } cmd = { 'jsonrpc': '2.0', 'method': 'Favourites.AddFavourite', 'params': { 'title': channel_name, 'type': 'media', 'path': _url + '?' + urllib.urlencode(params) }, 'id': '1' } debug_dict = json.loads(xbmc.executeJSONRPC(json.dumps(cmd))) addon_log('channel_to_favs response: %s' % debug_dict)
def addon_enabled(self, addon_id): rpc_request = json.dumps({"jsonrpc": "2.0", "method": "Addons.GetAddonDetails", "id": 1, "params": {"addonid": "%s" % addon_id, "properties": ["enabled"]} }) response = json.loads(xbmc.executeJSONRPC(rpc_request)) try: return response['result']['addon']['enabled'] is True except KeyError: message = response['error']['message'] code = response['error']['code'] error = 'Requested |%s| received error |%s| and code: |%s|' % (rpc_request, message, code) xbmc.log(error, xbmc.LOGDEBUG) return False
def set_addon_enabled(self, addon_id, enabled=True): rpc_request = json.dumps({"jsonrpc": "2.0", "method": "Addons.SetAddonEnabled", "id": 1, "params": {"addonid": "%s" % addon_id, "enabled": enabled} }) response = json.loads(xbmc.executeJSONRPC(rpc_request)) try: return response['result'] == 'OK' except KeyError: message = response['error']['message'] code = response['error']['code'] error = 'Requested |%s| received error |%s| and code: |%s|' % (rpc_request, message, code) xbmc.log(error, xbmc.LOGDEBUG) return False
def __getattr__(self, method): def handler(**kwargs): command = { 'jsonrpc': '2.0', 'id': 1, 'method': '{0}.{1}'.format(self.family, method) } if kwargs: command['params'] = kwargs # xbmc.log(json.dumps(command)) ret = json.loads(xbmc.executeJSONRPC(json.dumps(command))) if ret: if 'error' in ret: raise self.Exception(ret['error']) else: return ret['result'] else: return None return handler
def get_episode_details(episode_id): postdata = json.dumps({"jsonrpc": "2.0", "id": 1, 'method': 'VideoLibrary.GetEpisodeDetails', "params": { 'episodeid': episode_id, "properties": ["season", "episode", "tvshowid", "playcount", "file", "resume"] }}) json_query = xbmc.executeJSONRPC(postdata) json_query = unicode(json_query, 'utf-8', errors='ignore') json_query = json.loads(json_query) if 'error' in json_query: xbmc.log('%s: ERROR: %s' % (ADDONID, json_query['error']['stack']['message'])) return None json_query = json_query['result']['episodedetails'] return json_query
def executeJSON(request): """Execute JSON-RPC Command Args: request: Dictionary with JSON-RPC Commands Found code in xbmc-addon-service-watchedlist """ rpccmd = json.dumps(request) # create string from dict json_query = xbmc.executeJSONRPC(rpccmd) json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = json.loads(json_query) return json_response # This class is the interface between the internal default settings and the user. # The user adjust the settings to his/her likings in Kodi. This class will make # sure that the addon knows that the user changed a setting.
def execute_jsonrpc(command): if not isinstance(command, basestring): command = json.dumps(command) response = xbmc.executeJSONRPC(command) return json.loads(response)
def _get_kodi_json(method, params): '''helper to get data from the kodi json database''' json_response = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method" : "%s", "params": %s, "id":1 }' % (method, params.encode("utf-8"))) jsonobject = json.loads(json_response.decode('utf-8', 'replace')) if 'result' in jsonobject: jsonobject = jsonobject['result'] return jsonobject
def Kodi17(): xbmc_version = re.search('^(\d+)', xbmc.getInfoLabel( "System.BuildVersion" )) if xbmc_version: xbmc_version = int(xbmc_version.group(1)) else: xbmc_version = 1 if xbmc_version >= 16.9: dependencies = [] import glob folder = xbmc.translatePath('special://home/addons/') for DEPEND in glob.glob(folder+'*.*'): try:dependencies.append(DEPEND.rsplit('\\', 1)[1]) except:dependencies.append(DEPEND.rsplit('/', 1)[1]) for THEPLUGIN in dependencies: query = '{"jsonrpc":"2.0", "method":"Addons.SetAddonEnabled","params":{"addonid":"%s","enabled":true}, "id":1}' % (THEPLUGIN) xbmc.executeJSONRPC(query) xbmc.executebuiltin('UpdateLocalAddons') xbmc.executebuiltin("UpdateAddonRepos")
def getBandwidthLimit(): json_result = xbmc.executeJSONRPC( '{"jsonrpc":"2.0","method":"Settings.GetSettingValue","params":{"setting":"network.bandwidth"},"id":1}') data_object = json.loads(json_result) return data_object['result']['value']
def get_inputstream_addon(self): """Checks if the inputstream addon is installed & enabled. Returns the type of the inputstream addon used and if it's enabled, or None if not found. Returns ------- :obj:`tuple` of obj:`str` and bool, or None Inputstream addon and if it's enabled, or None """ is_type = 'inputstream.adaptive' is_enabled = False payload = { 'jsonrpc': '2.0', 'id': 1, 'method': 'Addons.GetAddonDetails', 'params': { 'addonid': is_type, 'properties': ['enabled'] } } response = xbmc.executeJSONRPC(json.dumps(payload)) data = json.loads(response) if 'error' not in data.keys(): if isinstance(data.get('result'), dict): if isinstance(data.get('result').get('addon'), dict): is_enabled = data.get('result').get('addon').get('enabled') return (is_type, is_enabled) return (None, is_enabled)
def movietitle_to_id(self, title): query = { "jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": { "properties": ["title"] }, "id": "libMovies" } try: rpc_result = xbmc.executeJSONRPC( jsonrpccommand=json.dumps(query, encoding='utf-8')) json_result = json.loads(rpc_result) if 'result' in json_result and 'movies' in json_result['result']: json_result = json_result['result']['movies'] for movie in json_result: # Switch to ascii/lowercase and remove special chars and spaces # to make sure best possible compare is possible titledb = movie['title'].encode('ascii', 'ignore') titledb = re.sub(r'[?|$|!|:|#|\.|\,|\'| ]', r'', titledb).lower().replace('-', '') if '(' in titledb: titledb = titledb.split('(')[0] titlegiven = title.encode('ascii','ignore') titlegiven = re.sub(r'[?|$|!|:|#|\.|\,|\'| ]', r'', titlegiven).lower().replace('-', '') if '(' in titlegiven: titlegiven = titlegiven.split('(')[0] if titledb == titlegiven: return movie['movieid'] return '-1' except Exception: return '-1'
def showtitle_to_id(self, title): query = { "jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": { "properties": ["title", "genre"] }, "id": "libTvShows" } try: rpc_result = xbmc.executeJSONRPC( jsonrpccommand=json.dumps(query, encoding='utf-8')) json_result = json.loads(rpc_result) if 'result' in json_result and 'tvshows' in json_result['result']: json_result = json_result['result']['tvshows'] for tvshow in json_result: # Switch to ascii/lowercase and # remove special chars and spaces # to make sure best possible compare is possible titledb = tvshow['label'].encode('ascii', 'ignore') titledb = re.sub( pattern=r'[?|$|!|:|#|\.|\,|\'| ]', repl=r'', string=titledb).lower().replace('-', '') if '(' in titledb: titledb = titledb.split('(')[0] titlegiven = title.encode('ascii', 'ignore') titlegiven = re.sub( pattern=r'[?|$|!|:|#|\.|\,|\'| ]', repl=r'', string=titlegiven).lower().replace('-', '') if '(' in titlegiven: titlegiven = titlegiven.split('(')[0] if titledb == titlegiven: return tvshow['tvshowid'], tvshow['genre'] return '-1', '' except Exception: return '-1', ''
def get_show_content_by_id(self, showid, showseason, showepisode): showseason = int(showseason) showepisode = int(showepisode) props = ["season", "episode", "plot", "fanart", "art"] query = { "jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": { "properties": props, "tvshowid": int(showid[0]) }, "id": "1" } try: rpc_result = xbmc.executeJSONRPC( jsonrpccommand=json.dumps(query, encoding='utf-8')) json_result = json.loads(rpc_result) result = json_result.get('result', None) if result is not None and 'episodes' in result: result = result['episodes'] for episode in result: in_season = episode['season'] == showseason in_episode = episode['episode'] == showepisode if in_season and in_episode: infos = {} if 'plot' in episode and len(episode['plot']) > 0: infos.update({ 'plot': episode['plot'], 'genre': showid[1]}) art = {} if 'fanart' in episode and len(episode['fanart']) > 0: art.update({'fanart': episode['fanart']}) if 'art' in episode and len(episode['art']['season.poster']) > 0: art.update({ 'thumb': episode['art']['season.poster']}) return infos, art return False except Exception: return False
def get_movie_content_by_id(self, movieid): query = { "jsonrpc": "2.0", "method": "VideoLibrary.GetMovieDetails", "params": { "movieid": movieid, "properties": [ "genre", "plot", "fanart", "thumbnail", "art"] }, "id": "libMovies" } try: rpc_result = xbmc.executeJSONRPC( jsonrpccommand=json.dumps(query, encoding='utf-8')) json_result = json.loads(rpc_result) result = json_result.get('result', None) if result is not None and 'moviedetails' in result: result = result.get('moviedetails', {}) infos = {} if 'genre' in result and len(result['genre']) > 0: infos.update({'genre': json_result['genre']}) if 'plot' in result and len(result['plot']) > 0: infos.update({'plot': result['plot']}) art = {} if 'fanart' in result and len(result['fanart']) > 0: art.update({'fanart': result['fanart']}) if 'thumbnail' in result and len(result['thumbnail']) > 0: art.update({'thumb': result['thumbnail']}) if 'art' in json_result and len(result['art']['poster']) > 0: art.update({'poster': result['art']['poster']}) return infos, art return False except Exception: return False
def executeJSON(request): # ================================================================= # Execute JSON-RPC Command # Args: # request: Dictionary with JSON-RPC Commands # Found code in xbmc-addon-service-watchedlist # ================================================================= rpccmd = json.dumps(request) # create string from dict json_query = xbmc.executeJSONRPC(rpccmd) json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = json.loads(json_query) return json_response
def json_query(query): if not "jsonrpc" in query: query["jsonrpc"] = "2.0" if not "id" in query: query["id"] = 1 xbmc_request = json.dumps(query) raw = xbmc.executeJSONRPC(xbmc_request) clean = unicode(raw, 'utf-8', errors='ignore') response = json.loads(clean) if "error" in response: raise RPCError(response["error"]) return response.get('result', response)
def set_json(jsonmethod, params): '''method to set info in the kodi json api''' kodi_json = {} kodi_json["jsonrpc"] = "2.0" kodi_json["method"] = jsonmethod kodi_json["params"] = params kodi_json["id"] = 1 json_response = xbmc.executeJSONRPC(try_encode(json.dumps(kodi_json))) return json.loads(json_response.decode('utf-8', 'replace'))
def getJSONResponse(message): return simplejson.loads(xbmc.executeJSONRPC(message))
def get_xbmc_JSONRPC_response(json_query=""): try: response = xbmc.executeJSONRPC(json_query) response = unicode(response, 'utf-8', errors='ignore') response = json.loads(response) logger.info("streamondemand.channels.database jsonrpc %s" % response) except Exception, e: logger.info("streamondemand.channels.database jsonrpc error: %s" % str(e)) response = None return response
def get_xbmc_jsonrpc_response(json_query=""): try: response = xbmc.executeJSONRPC(json_query) response = unicode(response, 'utf-8', errors='ignore') response = json.loads(response) logger.info("streamondemand.channels.database jsonrpc %s" % response) except Exception, e: logger.info("streamondemand.channels.database jsonrpc error: %s" % str(e)) response = None return response
def get_xbmc_jsonrpc_response(json_query=""): try: response = xbmc.executeJSONRPC(json_query) response = unicode(response, 'utf-8', errors='ignore') response = json.loads(response) logger.info("streamondemand-pureita.channels.database jsonrpc %s" % response) except Exception, e: logger.info("streamondemand-pureita.channels.database jsonrpc error: %s" % str(e)) response = None return response
def kodiJsonRequest(params): data = json.dumps(params) request = xbmc.executeJSONRPC(data) try: response = json.loads(request) except UnicodeDecodeError: response = json.loads(request.decode('utf-8', 'ignore')) try: if 'result' in response: return response['result'] return None except KeyError: logger.warn("[%s] %s" % (params['method'], response['error']['message'])) return None
def add_dummy_favorite(): json_rpc_command={"jsonrpc": "2.0", "method": "Favourites.AddFavourite", 'params': { 'title': 'dummy', 'type': 'script', 'path': 'dummy_command_enough_to_e_unique', }, 'id': '1' } a=xbmc.executeJSONRPC(json.dumps(json_rpc_command)) log("dummy favorite:" + repr(a))
def json_query(query, ret): try: xbmc_request = json.dumps(query) result = xbmc.executeJSONRPC(xbmc_request) #print result #result = unicode(result, 'utf-8', errors='ignore') #log('result = ' + str(result)) if ret: return json.loads(result)['result'] else: return json.loads(result) except: return {} #https://github.com/russellballestrini/nested-lookup/blob/master/nested_lookup/nested_lookup.py
def __init__(self, version, releasename, appname): super(XbmcSystemVersion, self).__init__(version, releasename, appname) try: json_query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Application.GetProperties", ' '"params": {"properties": ["version", "name"]}, "id": 1 }') json_query = unicode(json_query, 'utf-8', errors='ignore') json_query = json.loads(json_query) version_installed = json_query['result']['version'] self._version = (version_installed.get('major', 1), version_installed.get('minor', 0)) self._appname = json_query['result']['name'] except: self._version = (1, 0) # Frodo self._appname = 'Unknown Application' self._releasename = 'Unknown Release' if (19, 0) > self._version >= (18, 0): self._releasename = 'Leia' elif self._version >= (17, 0): self._releasename = 'Krypton' elif self._version >= (16, 0): self._releasename = 'Jarvis' elif self._version >= (15, 0): self._releasename = 'Isengard' elif self._version >= (14, 0): self._releasename = 'Helix' elif self._version >= (13, 0): self._releasename = 'Gotham' elif self._version >= (12, 0): self._releasename = 'Frodo'
def get_kodi_json(method, params): json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "%s", "params": %s, "id": 1}' % (method, params)) json_query = unicode(json_query, 'utf-8', errors='ignore') return json.loads(json_query)
def __init__(self, version, releasename, appname): super(XbmcSystemVersion, self).__init__(version, releasename, appname) try: json_query = xbmc.executeJSONRPC( '{ "jsonrpc": "2.0", "method": "Application.GetProperties", "params": {"properties": ["version", "name"]}, "id": 1 }') json_query = unicode(json_query, 'utf-8', errors='ignore') json_query = json.loads(json_query) version_installed = [] version_installed = json_query['result']['version'] self._version = (version_installed.get('major', 1), version_installed.get('minor', 0)) self._appname = json_query['result']['name'] pass except: self._version = (1, 0) # Frodo self._appname = 'Unknown Application' pass self._releasename = 'Unknown XBMC Release' if self._version >= (12, 0): self._releasename = 'Frodo' pass if self._version >= (13, 0): self._releasename = 'Gotham' pass if self._version >= (14, 0): self._releasename = 'Helix' pass if self._version >= (15, 0): self._releasename = 'Isengard' pass if self._version >= (16, 0): self._releasename = 'Jarvis' pass if self._version >= (17, 0): self._releasename = 'Krypton' pass
def get_shows(): postdata = json.dumps({"jsonrpc": "2.0", "id": 1, 'method': 'VideoLibrary.GetTVShows', "params": { "properties": ["imdbnumber"] }}) json_query = xbmc.executeJSONRPC(postdata) json_query = unicode(json_query, 'utf-8', errors='ignore') json_query = json.loads(json_query)['result']['tvshows'] return json_query
def get_show_details(show_id): postdata = json.dumps({"jsonrpc": "2.0", "id": 1, 'method': 'VideoLibrary.GetTVShowDetails', "params": { 'tvshowid': show_id, "properties": ["imdbnumber"] }}) json_query = xbmc.executeJSONRPC(postdata) json_query = unicode(json_query, 'utf-8', errors='ignore') json_query = json.loads(json_query)['result']['tvshowdetails'] return json_query
def get_episodes(show_id): postdata = json.dumps({"jsonrpc": "2.0", "id": 1, 'method': 'VideoLibrary.GetEpisodes', "params": { 'tvshowid': show_id, "properties": ["season", "episode", "playcount", "resume"] }}) json_query = xbmc.executeJSONRPC(postdata) json_query = json.loads(json_query) if 'error' in json_query: xbmc.log('%s: ERROR: %s' % (ADDONID, json_query['error']['stack']['message'])) return None json_query = json_query['result']['episodes'] return json_query
def set_watched(episode_id, watched): postdata = json.dumps({"jsonrpc": "2.0", "id": 1, 'method': 'VideoLibrary.SetEpisodeDetails', "params": { 'episodeid': episode_id, 'playcount': 1 if watched else 0, }}) xbmc.executeJSONRPC(postdata)
def ShowStats(self, showAddons = False): # Get all Files in Thumbnails folder and all Textures in Database self.ExploreThumbnailsFolder(thumbnailsFolder) jSonQuery = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Textures.GetTextures", "id": 1}') jSon = json.loads(jSonQuery) try: if jSon['result'].has_key('textures'): getTextures = jSon['result']['textures'] except: getTextures = [] statsT = normalize(addonLanguage(32108)) + ": " + humanReadableSizeOf(self.thumbnailFileSize) + ", " + str(len(self.thumbnailFileList)) + " " + normalize(addonLanguage(32107)) + ", " + str(len(getTextures)) + " " + normalize(addonLanguage(32108)) statsA = "" if showAddons: # Compute addon size and number of files. totalAddonSize = 0 totalAddonFiles = 0 addonData = os.path.join(userdataFolder, "addon_data") for item in os.listdir(addonData): totalAddonSize = totalAddonSize + self.GetFolderSize(os.path.join(addonData, item)) totalAddonFiles = totalAddonFiles + 1 addonRollback = os.path.join(homeFolder, "addons", "packages") for item in os.listdir(addonRollback): totalAddonSize = totalAddonSize + os.stat(os.path.join(addonRollback, item)).st_size totalAddonFiles = totalAddonFiles + 1 statsA = normalize(addonLanguage(32109)) + ": " + humanReadableSizeOf(totalAddonSize) + ", " + str(totalAddonFiles) + " " + normalize(addonLanguage(32107)) # Show stats xbmcgui.Dialog().ok(addonName + " - " + normalize(addonLanguage(32106)), statsT, statsA)
def getInputstreamAddon(): r = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "id": 1, "method": "Addons.GetAddonDetails", "params": {"addonid":"inputstream.adaptive", "properties": ["enabled"]}}') data = json.loads(r) if not "error" in data.keys(): if data["result"]["addon"]["enabled"] == True: return True return None
def getJSON(self,method,params): json_response = xbmc.executeJSONRPC('{ "jsonrpc" : "2.0" , "method" : "' + method + '" , "params" : ' + params + ' , "id":1 }') jsonobject = json.loads(json_response.decode('utf-8','replace')) if(jsonobject.has_key('result')): return jsonobject['result'] else: self.log("no result " + str(jsonobject),xbmc.LOGDEBUG) return None
def check_plg(): js_resp = xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Addons.GetAddons", "id":1}') if int(xbmc.getInfoLabel("System.BuildVersion" )[0:2]) > 14: ln = 1 else: ln = 2 if len(re.findall(r'blstfusion', js_resp)) > ln: Notify ('%s %s' % (__scriptname__, __version__) , '[COLOR FFFF0000]confilct ![/COLOR]') return False else: return True
def get_data(payload): """ obtiene la información de la llamada JSON-RPC con la información pasada en payload @type payload: dict @param payload: data :return: """ logger.info("payload: %s" % payload) # Required header for XBMC JSON-RPC calls, otherwise you'll get a 415 HTTP response code - Unsupported media type headers = {'content-type': 'application/json'} if config.get_setting("library_mode", "biblioteca"): try: try: xbmc_port = config.get_setting("xbmc_puerto", "biblioteca") except: xbmc_port = 0 xbmc_json_rpc_url = "http://" + config.get_setting("xbmc_host", "biblioteca") + ":" + str( xbmc_port) + "/jsonrpc" req = urllib2.Request(xbmc_json_rpc_url, data=jsontools.dump_json(payload), headers=headers) f = urllib2.urlopen(req) response = f.read() f.close() logger.info("get_data: response %s" % response) data = jsontools.load_json(response) except Exception, ex: template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) logger.error("get_data: error en xbmc_json_rpc_url: %s" % message) data = ["error"] else: try: data = jsontools.load_json(xbmc.executeJSONRPC(jsontools.dump_json(payload))) except Exception, ex: template = "An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) logger.error("get_data:: error en xbmc.executeJSONRPC: {0}". format(message)) data = ["error"] logger.info("data: %s" % data) return data