Python xbmc 模块,LOGERROR 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用xbmc.LOGERROR

项目:screensaver.kaster    作者:enen92    | 项目源码 | 文件源码
def get_own_pictures(path):
    _, files = xbmcvfs.listdir(xbmc.translatePath(path))
    images_dict = {}
    image_file = os.path.join(xbmc.translatePath(path), "images.json")
    if xbmcvfs.exists(image_file):
        with open(image_file, "r") as f:
            try:
                images_dict = json.loads(f.read())
            except ValueError:
                kodiutils.log(kodiutils.get_string(32010), xbmc.LOGERROR)
    for _file in files:
        if _file.endswith(('.png', '.jpg', '.jpeg')):
            returned_dict = {
                "url": os.path.join(xbmc.translatePath(path), _file),
                "private": True
            }
            if images_dict:
                for image in images_dict:
                    if "image" in image.keys() and image["image"] == _file:
                        if "line1" in image.keys():
                            returned_dict["line1"] = image["line1"]
                        if "line2" in image.keys():
                            returned_dict["line2"] = image["line2"]
            yield returned_dict
项目:konsodi    作者:kharts    | 项目源码 | 文件源码
def log(msg, level=xbmc.LOGNOTICE):
    """
    Outputs message to log file
    :param msg: message to output
    :param level: debug levelxbmc. Values:
    xbmc.LOGDEBUG = 0
    xbmc.LOGERROR = 4
    xbmc.LOGFATAL = 6
    xbmc.LOGINFO = 1
    xbmc.LOGNONE = 7
    xbmc.LOGNOTICE = 2
    xbmc.LOGSEVERE = 5
    xbmc.LOGWARNING = 3
    """

    log_message = u'{0}: {1}'.format(addonID, msg)
    xbmc.log(log_message.encode("utf-8"), level)
项目:script.module.thetvdb    作者:marcelveldt    | 项目源码 | 文件源码
def get_data(self, endpoint, prefer_localized=False):
        '''grab the results from the api'''
        data = {}
        url = 'https://api.thetvdb.com/' + endpoint
        headers = {'Content-Type': 'application/json',
                   'Accept': 'application/json',
                   'User-agent': 'Mozilla/5.0', 'Authorization': 'Bearer %s' % self._get_token()}
        if prefer_localized:
            headers["Accept-Language"] = KODI_LANGUAGE
        try:
            response = requests.get(url, headers=headers, timeout=20)
            if response and response.content and response.status_code == 200:
                data = json.loads(response.content.decode('utf-8', 'replace'))
            elif response.status_code == 401:
                # token expired, refresh it and repeat our request
                self._log_msg("Token expired, refreshing...")
                headers['Bearer'] = self._get_token(True)
                response = requests.get(url, headers=headers, timeout=5)
                if response and response.content and response.status_code == 200:
                    data = json.loads(response.content.decode('utf-8', 'replace'))
            if data.get("data"):
                data = data["data"]
        except Exception as exc:
            self._log_msg("Exception in get_data --> %s" % repr(exc), xbmc.LOGERROR)
        return data
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def get_album_json_thread(self):
        try:
            while not xbmc.abortRequested and not self.abortAlbumThreads:
                try:
                    album_id = self.albumQueue.get_nowait()
                except:
                    break
                try:
                    self.get_album(album_id, withCache=False)
                except requests.HTTPError as e:
                    r = e.response
                    msg = _T(30505)
                    try:
                        msg = r.reason
                        msg = r.json().get('userMessage')
                    except:
                        pass
                    log('Error getting Album ID %s' % album_id, xbmc.LOGERROR)
                    if r.status_code == 429 and not self.abortAlbumThreads:
                        self.abortAlbumThreads = True
                        log('Too many requests. Aborting Workers ...', xbmc.LOGERROR)
                        self.albumQueue._init(9999)
                        xbmcgui.Dialog().notification(plugin.name, msg, xbmcgui.NOTIFICATION_ERROR)
        except Exception, e:
            traceback.print_exc()
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def selectPlaylistDialog(self, headline=None, allowNew=False):
        if not self._session.is_logged_in:
            return None
        xbmc.executebuiltin("ActivateWindow(busydialog)")
        try:
            if not headline:
                headline = _T(30238)
            items = self.playlists()
            dialog = xbmcgui.Dialog()
            item_list = [item.title for item in items]
            if allowNew:
                item_list.append(_T(30237))
        except Exception, e:
            log(str(e), level=xbmc.LOGERROR)
            xbmc.executebuiltin("Dialog.Close(busydialog)")
            return None
        xbmc.executebuiltin("Dialog.Close(busydialog)")
        selected = dialog.select(headline, item_list)
        if selected >= len(items):
            item = self.newPlaylistDialog()
            return item
        elif selected >= 0:
            return items[selected]
        return None
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def log(self, txt = '', level=xbmc.LOGDEBUG):
        ''' Log a text into the Kodi-Logfile '''
        try:
            if self.detailLevel > 0 or level == xbmc.LOGERROR:
                if self.detailLevel == 2 and level == xbmc.LOGDEBUG:
                    # More Logging
                    level = xbmc.LOGNOTICE
                elif self.detailLevel == 3 and (level == xbmc.LOGDEBUG or level == xbmc.LOGSEVERE):
                    # Complex Logging
                    level = xbmc.LOGNOTICE
                if level != xbmc.LOGSEVERE:
                    if isinstance(txt, unicode):
                        txt = unidecode(txt)
                    xbmc.log(b"[%s] %s" % (self.pluginName, txt), level) 
        except:
            xbmc.log(b"[%s] Unicode Error in message text" % self.pluginName, xbmc.LOGERROR)
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def emit(self, record):
        if record.levelno < logging.WARNING and self._modules and not record.name in self._modules:
            # Log INFO and DEBUG only with enabled modules
            return
        levels = {
            logging.CRITICAL: xbmc.LOGFATAL,
            logging.ERROR: xbmc.LOGERROR,
            logging.WARNING: xbmc.LOGWARNING,
            logging.INFO: xbmc.LOGNOTICE,
            logging.DEBUG: xbmc.LOGSEVERE,
            logging.NOTSET: xbmc.LOGNONE,
        }
        try:
            xbmc.log(self.format(record), levels[record.levelno])
        except:
            try:
                xbmc.log(self.format(record).encode('utf-8', 'ignore'), levels[record.levelno])
            except:
                xbmc.log(b"[%s] Unicode Error in message text" % self.pluginName, levels[record.levelno])
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def user_playlist_remove_album(playlist_id, item_id, dialog=True):
    playlist = session.get_playlist(playlist_id)
    ok = True
    if dialog:
        ok = xbmcgui.Dialog().yesno(_T(30247) % playlist.title, _T(30246))
    if ok:
        xbmc.executebuiltin('ActivateWindow(busydialog)')
        try:
            items = session.get_playlist_tracks(playlist)
            for item in items:
                if '%s' % item.album.id == '%s' % item_id:
                    session.user.remove_playlist_entry(playlist, entry_no=item._playlist_pos)
                    break # Remove only one Item
        except Exception, e:
            log(str(e), level=xbmc.LOGERROR)
            traceback.print_exc()
        xbmc.executebuiltin('Dialog.Close(busydialog)')
        xbmc.executebuiltin('Container.Refresh()')
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def user_playlist_move_entry(playlist_id, entry_no, item_id):
    dialog = xbmcgui.Dialog()
    playlist = session.user.selectPlaylistDialog(headline=_T(30248), allowNew=True)
    if playlist and playlist.id <> playlist_id:
        xbmc.executebuiltin( "ActivateWindow(busydialog)" )
        try:
            ok = session.user.add_playlist_entries(playlist=playlist, item_ids=[item_id])
            if ok:
                ok = session.user.remove_playlist_entry(playlist_id, entry_no=entry_no)
            else:
                dialog.notification(plugin.name, _T('API Call Failed'), xbmcgui.NOTIFICATION_ERROR)
        except Exception, e:
            log(str(e), level=xbmc.LOGERROR)
            traceback.print_exc()
        xbmc.executebuiltin( "Dialog.Close(busydialog)" )
        xbmc.executebuiltin('Container.Refresh()')
项目:script.tvguide.fullscreen    作者:primaeval    | 项目源码 | 文件源码
def __init__(self):
        # Class initialisation.  Fails with a RuntimeError exception if VPN Manager add-on is not available, or too old
        self.filtered_addons = []
        self.filtered_windows = []
        self.primary_vpns = []
        self.last_updated = 0
        self.refreshLists()
        self.default = self.getConnected()
        xbmc.log("VPN Mgr API : Default is " + self.default, level=xbmc.LOGDEBUG)
        self.timeout = 30
        if not xbmc.getCondVisibility("System.HasAddon(service.vpn.manager)"):
            xbmc.log("VPN Mgr API : VPN Manager is not installed, cannot use filtering", level=xbmc.LOGERROR)
            raise RuntimeError("VPN Manager is not installed")
        else:
            v = int((xbmcaddon.Addon("service.vpn.manager").getAddonInfo("version").strip()).replace(".",""))
            if v < 310:
                raise RuntimeError("VPN Manager " + str(v) + " installed, but needs to be v3.1.0 or later")
项目:plugin.video.amazon65    作者:phil65    | 项目源码 | 文件源码
def getURL(url, host=BASE_URL.split('//')[1], useCookie=False, silent=False, headers=None):
    cj = cookielib.LWPCookieJar()
    if useCookie:
        if isinstance(useCookie, bool):
            cj = mechanizeLogin()
        else:
            cj = useCookie
        if isinstance(cj, bool):
            return False
    dispurl = re.sub('(?i)%s|%s|&token=\w+' % (tvdb, tmdb), '', url).strip()
    if not silent:
        Log('getURL: ' + dispurl)
    if not headers:
        headers = [('User-Agent', UserAgent), ('Host', host)]
    try:
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), urllib2.HTTPRedirectHandler)
        opener.addheaders = headers
        usock = opener.open(url)
        response = usock.read()
        usock.close()
    except urllib2.URLError, e:
        Log('Error reason: %s' % e, xbmc.LOGERROR)
        return False
    return response
项目:plugin.video.amazon65    作者:phil65    | 项目源码 | 文件源码
def getATVURL(url):
    try:
        opener = urllib2.build_opener()
        Log('ATVURL --> url = ' + url)
        hmac_key = binascii.unhexlify('f5b0a28b415e443810130a4bcb86e50d800508cc')
        sig = hmac.new(hmac_key, url, hashlib.sha1)
        androidsig = base64.encodestring(sig.digest()).replace('\n', '')
        opener.addheaders = [('x-android-sign', androidsig)]
        usock = opener.open(url)
        response = usock.read()
        usock.close()
    except urllib2.URLError, e:
        Log('Error reason: %s' % e, xbmc.LOGERROR)
        return False
    else:
        return response
项目:xbmctopython    作者:pybquillast    | 项目源码 | 文件源码
def enableService(self, serviceId, addonFile):
        import xbmc
        try:
            srvThread = execfile(addonFile, sys.modules['__main__'].__dict__)
        except Exception as e:
            srvThread = None
            msg, loglevel = str(e), xbmc.LOGERROR
        else:
            msg = 'Service %s, succesfully loaded from %s'
            msg, loglevel = msg % (serviceId, addonFile), xbmc.LOGDEBUG
        finally:
            xbmc.log(msg, loglevel)
            if loglevel == xbmc.LOGERROR:
                msg = traceback.format_exc()
                xbmc.log(msg, xbmc.LOGERROR)
        return srvThread
项目:xbmctopython    作者:pybquillast    | 项目源码 | 文件源码
def run(self, url):
        xbmc = self.theGlobals['xbmc']
        urlScheme = urlparse.urlparse(url)
        if urlScheme.scheme != 'plugin': return             # Plugin diferente
        pluginId, urlArgs = urllib.splitquery(url)
        self.theGlobals['sys'].argv = [pluginId, self.theGlobals['sys'].argv[1] + 1, '?' + (urlArgs or '')]
        self.addonID = actualID = urlScheme.netloc
        addonDir = xbmc.translatePath('special://home/addons/' + actualID)
        if addonDir.startswith('vrt:%s' % os.path.sep):
            self.vrtDisk.installPathHook()
            sys.path.insert(0, addonDir)
            sourceCode = self.getVrtDiskAddonSource()
        else:
            sourceCode = self.getCompiledAddonSource(actualID)
            self.importer.setAddonDir(addonDir)
        try:
            exec(sourceCode, self.theGlobals)
        except Exception as e:
            xbmc.log(str(e), xbmc.LOGERROR)
            msg = traceback.format_exc()
            xbmc.log(msg, xbmc.LOGERROR)
            self.answ = None
        return self.answ
项目:plex-for-kodi-mod    作者:mrclemds    | 项目源码 | 文件源码
def ERROR(txt='', hide_tb=False, notify=False):
    if isinstance(txt, str):
        txt = txt.decode("utf-8")
    short = str(sys.exc_info()[1])
    if hide_tb:
        xbmc.log('script.plex: ERROR: {0} - {1}'.format(txt, short), xbmc.LOGERROR)
        return short

    import traceback
    tb = traceback.format_exc()
    xbmc.log("_________________________________________________________________________________", xbmc.LOGERROR)
    xbmc.log('script.plex: ERROR: ' + txt, xbmc.LOGERROR)
    for l in tb.splitlines():
        xbmc.log('    ' + l, xbmc.LOGERROR)
    xbmc.log("_________________________________________________________________________________", xbmc.LOGERROR)
    xbmc.log("`", xbmc.LOGERROR)
    if notify:
        showNotification('ERROR: {0}'.format(short))
    return short
项目:soap4me-proxy    作者:eschava    | 项目源码 | 文件源码
def __init__(self):
        watched_status = WatchedStatus()

        api = SoapApi(watched_status)
        watched_status.soap_api = api
        api.main()

        try:
            httpd = SocketServer.TCPServer(("", KodiConfig.get_web_port()), WebHandler)
            httpd.api = api
            kodi_waiter = threading.Thread(target=self.kodi_waiter_thread, args=(httpd, watched_status,))
            kodi_waiter.start()
            httpd.serve_forever()
        except:
            message_error("Cannot create web-server, port is busy")
            xbmc.log('%s: %s' % (ADDONID, format_exc()), xbmc.LOGERROR)
            #raise
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def __init__(self):
        # Class initialisation.  Fails with a RuntimeError exception if VPN Manager add-on is not available, or too old
        self.filtered_addons = []
        self.filtered_windows = []
        self.primary_vpns = []
        self.last_updated = 0
        self.refreshLists()
        self.default = self.getConnected()
        xbmc.log("VPN Mgr API : Default is " + self.default, level=xbmc.LOGDEBUG)
        self.timeout = 30
        if not xbmc.getCondVisibility("System.HasAddon(service.vpn.manager)"):
            xbmc.log("VPN Mgr API : VPN Manager is not installed, cannot use filtering", level=xbmc.LOGERROR)
            raise RuntimeError("VPN Manager is not installed")
        else:
            v = int((xbmcaddon.Addon("service.vpn.manager").getAddonInfo("version").strip()).replace(".",""))
            if v < 310:
                raise RuntimeError("VPN Manager " + str(v) + " installed, but needs to be v3.1.0 or later")
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def log_exception(modulename, exceptiondetails):
    '''helper to properly log exception details'''
    log_msg(format_exc(sys.exc_info()), xbmc.LOGNOTICE)
    log_msg("ERROR in %s ! --> %s" % (modulename, exceptiondetails), xbmc.LOGERROR)
    dialog = xbmcgui.Dialog()
    dialog.notification(
        "Skin Helper Backup",
        "Error while executing, please check your kodi logfile.",
        xbmcgui.NOTIFICATION_ERROR)
    del dialog
项目:plugin.video.bdyun    作者:caasiu    | 项目源码 | 文件源码
def log(message,loglevel=xbmc.LOGNOTICE):
    """"save message to kodi.log.

    Args:
        message: has to be unicode, http://wiki.xbmc.org/index.php?title=Add-on_unicode_paths#Logging
        loglevel: xbmc.LOGDEBUG, xbmc.LOGINFO, xbmc.LOGNOTICE, xbmc.LOGWARNING, xbmc.LOGERROR, xbmc.LOGFATAL
    """
    xbmc.log(encode(__addon_id__ + u": " + message), level=loglevel)
项目:konsodi    作者:kharts    | 项目源码 | 文件源码
def log_exception(content):
    """
    Outputs content to log file
    :param content: content which should be output
    :return: None
    """

    if type(content) is str:
        message = unicode(content, "utf-8")
    else:
        message = content
    log(message, xbmc.LOGERROR)
项目:plugin.audio.spotify    作者:marcelveldt    | 项目源码 | 文件源码
def test_spotty(self, binary_path):
        '''self-test spotty binary'''
        try:
            st = os.stat(binary_path)
            os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
            args = [
                binary_path,
                "-n", "selftest",
                "-x", "--disable-discovery"
            ]
            startupinfo = None
            if os.name == 'nt':
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
            spotty = subprocess.Popen(
                args,
                startupinfo=startupinfo,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                bufsize=0)
            stdout, stderr = spotty.communicate()
            log_msg(stdout)
            if "ok spotty" in stdout:
                return True
            elif xbmc.getCondVisibility("System.Platform.Windows"):
                log_msg("Unable to initialize spotty binary for playback."
                        "Make sure you have the VC++ 2015 runtime installed.", xbmc.LOGERROR)
        except Exception as exc:
            log_exception(__name__, exc)
        return False
项目:Python-GoogleDrive-VideoStream    作者:ddurdle    | 项目源码 | 文件源码
def debugger(self):
        try:

            remote_debugger = settings.getSetting('remote_debugger')
            remote_debugger_host = settings.getSetting('remote_debugger_host')

            # append pydev remote debugger
            if remote_debugger == 'true':
                # Make pydev debugger works for auto reload.
                # Note pydevd module need to be copied in XBMC\system\python\Lib\pysrc
                import pysrc.pydevd as pydevd
                # stdoutToServer and stderrToServer redirect stdout and stderr to eclipse console
                pydevd.settrace(remote_debugger_host, stdoutToServer=True, stderrToServer=True)
        except ImportError:
            xbmc.log(self.addon.getLocalizedString(30016), xbmc.LOGERROR)
            sys.exit(1)
        except :
            return




    ##
    # add a menu to a directory screen
    #   parameters: url to resolve, title to display, optional: icon, fanart, total_items, instance name
    ##
项目:Python-GoogleDrive-VideoStream    作者:ddurdle    | 项目源码 | 文件源码
def downloadGeneralFile(self, url, file, force=False):

        req = urllib2.Request(url, None, self.getHeadersList())

        # already downloaded
        if not force and xbmcvfs.exists(file) and xbmcvfs.File(file).size() > 0:
            return

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

        # if action fails, validate login
        try:
            f.write(urllib2.urlopen(req).read())
            f.close()

        except urllib2.URLError, e:
                self.refreshToken()
                req = urllib2.Request(url, None, self.getHeadersList())
                try:
                  f.write(urllib2.urlopen(req).read())
                  f.close()
                except urllib2.URLError, e:
                  xbmc.log(self.addon.getAddonInfo('name') + ': downloadGeneralFle ' + str(e), xbmc.LOGERROR)
                  return None
        #can't write to cache for some reason
        except IOError:
                return None
        return file
    ##
    # retrieve/download a general file
    #   parameters: title of video, whether to prompt for quality/format (optional), medial url object, package object, whether to force download (overwrite), whether folder is encrypted, folder name
    ##
项目:Python-GoogleDrive-VideoStream    作者:ddurdle    | 项目源码 | 文件源码
def downloadPicture(self, url, file):

        req = urllib2.Request(url, None, self.getHeadersList())

        # already downloaded
        if xbmcvfs.exists(file) and xbmcvfs.File(file).size() > 0:
            return

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

        # if action fails, validate login
        try:
            f.write(urllib2.urlopen(req).read())
            f.close()

        except urllib2.URLError, e:
                self.refreshToken()
                req = urllib2.Request(url, None, self.getHeadersList())
                try:
                  f.write(urllib2.urlopen(req).read())
                  f.close()
                except urllib2.URLError, e:
                  xbmc.log(self.addon.getAddonInfo('name') + ': downloadPicture ' + str(e), xbmc.LOGERROR)
                  return None
        #can't write to cache for some reason
        except IOError:
                return None
        return file
项目:Python-GoogleDrive-VideoStream    作者:ddurdle    | 项目源码 | 文件源码
def createWorksheet(self,url,title,cols,rows):

        header = { 'User-Agent' : self.user_agent, 'Authorization' : 'GoogleLogin auth=%s' % self.authorization.getToken('wise'), 'GData-Version' : '3.0',  'Content-Type': 'application/atom+xml' }

        entry = '<?xml version=\'1.0\' encoding=\'UTF-8\'?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:gs="http://schemas.google.com/spreadsheets/2006"><title>A worksheetdadf</title><gs:rowCount>100</gs:rowCount><gs:colCount>20</gs:colCount></entry>'

        req = urllib2.Request(url, entry, header)

        try:
            response = urllib2.urlopen(req)
        except urllib2.URLError, e:
          if e.code == 403 or e.code == 401:
            self.service.refreshToken()
            req = urllib2.Request(url, None, self.service.getHeadersList())
            try:
                response = urllib2.urlopen(req)
            except urllib2.URLError, e:
                xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
                return False
          else:
            xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
            return False


        response.read()
        response.close()

        return True

    #
    # returns a list of spreadsheets contained in the Google Docs account
    #
项目:Python-GoogleDrive-VideoStream    作者:ddurdle    | 项目源码 | 文件源码
def createHeaderRow(self,url):

        header = { 'User-Agent' : self.user_agent, 'Authorization' : 'GoogleLogin auth=%s' % self.authorization.getToken('wise'), 'GData-Version' : '3.0',  "If-Match" : '*', 'Content-Type': 'application/atom+xml'}

        entry = '<?xml version=\'1.0\' encoding=\'UTF-8\'?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended"> <gsx:hours>1</gsx:hours></entry>'

        req = urllib2.Request(url, entry, header)

        try:
            response = urllib2.urlopen(req)
        except urllib2.URLError, e:
          if e.code == 403 or e.code == 401:
            self.service.refreshToken()
            header = { 'User-Agent' : self.user_agent, 'Authorization' : 'GoogleLogin auth=%s' % self.authorization.getToken('wise'), 'GData-Version' : '3.0',  "If-Match" : '*', 'Content-Type': 'application/atom+xml'}
            req = urllib2.Request(url, entry, header)
            try:
                response = urllib2.urlopen(req)
            except urllib2.URLError, e:
                xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
                return False
          else:
            xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
            return False

        response.read()
        response.close()

        return True




    #
    # returns a list of worksheets with a link to their listfeeds
    #
项目:Python-GoogleDrive-VideoStream    作者:ddurdle    | 项目源码 | 文件源码
def createSpreadsheet(self):

        #header = { 'User-Agent' : self.user_agent, 'Authorization' : 'GoogleLogin auth=%s' % self.authorization.getToken('wise'), 'GData-Version' : '3.0',  'Content-Type': 'application/atom+xml' }

        entry = '{"properties": { "title": "TEST123" }}'
 #       entry = { 'properties' : {'title': 'TEST1234'}}

        url = self.API_URL #+ '?key=AIzaSyD-a9IF8KKYgoC3cpgS-Al7hLQDbugrDcw&alt=json'
#        url = 'https://sheets.googleapis.com/v4/spreadsheets/1lrARPXpjLAO-edm5J9p0UK7nmkukST6bv07u8ai1MY8'
        req = urllib2.Request(url, entry, self.service.getHeadersList(isPOST=True))

        #req = urllib2.Request(url,  json.dumps(entry), self.service.getHeadersList(isPOST=True, isJSON=True))
 #       req = urllib2.Request(url, None, self.service.getHeadersList())

        try:
            response = urllib2.urlopen(req)
        except urllib2.URLError, e:
          if e.code == 403 or e.code == 401:
            self.service.refreshToken()
            req = urllib2.Request(url, entry, self.service.getHeadersList(isPOST=True))
            try:
                response = urllib2.urlopen(req)
            except urllib2.URLError, e:
                xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
                return False
          else:
            xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
            return False


        response.read()
        response.close()

        return True

    #
    # append data to spreadsheet
    #
项目:Python-GoogleDrive-VideoStream    作者:ddurdle    | 项目源码 | 文件源码
def addRows(self, spreadsheetID):



        entry = '{"values": [[ "title", "TEST123" ]]}'

        url = self.API_URL + '/'+spreadsheetID+'/values/A1:append?valueInputOption=USER_ENTERED'#values/Sheet1!A1:A3?valueInputOption=USER_ENTERED'
#        url = 'https://sheets.googleapis.com/v4/spreadsheets/1lrARPXpjLAO-edm5J9p0UK7nmkukST6bv07u8ai1MY8'
        req = urllib2.Request(url, entry, self.service.getHeadersList(isPOST=True))

        #req = urllib2.Request(url,  json.dumps(entry), self.service.getHeadersList(isPOST=True, isJSON=True))
 #       req = urllib2.Request(url, None, self.service.getHeadersList())

        try:
            response = urllib2.urlopen(req)
        except urllib2.URLError, e:
          if e.code == 403 or e.code == 401:
            self.service.refreshToken()
            req = urllib2.Request(url, entry, self.service.getHeadersList(isPOST=True))
            try:
                response = urllib2.urlopen(req)
            except urllib2.URLError, e:
                xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
                return False
          else:
            xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
            return False


        response.read()
        response.close()

        return True



    #
    # returns a list of spreadsheets and a link to their worksheets
    #
项目:Python-GoogleDrive-VideoStream    作者:ddurdle    | 项目源码 | 文件源码
def createWorksheet(self,url,title,cols,rows):

        header = { 'User-Agent' : self.user_agent, 'Authorization' : 'GoogleLogin auth=%s' % self.authorization.getToken('wise'), 'GData-Version' : '3.0',  'Content-Type': 'application/atom+xml' }

        entry = '<?xml version=\'1.0\' encoding=\'UTF-8\'?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:gs="http://schemas.google.com/spreadsheets/2006"><title>A worksheetdadf</title><gs:rowCount>100</gs:rowCount><gs:colCount>20</gs:colCount></entry>'

        req = urllib2.Request(url, entry, header)

        try:
            response = urllib2.urlopen(req)
        except urllib2.URLError, e:
          if e.code == 403 or e.code == 401:
            self.service.refreshToken()
            req = urllib2.Request(url, None, self.service.getHeadersList())
            try:
                response = urllib2.urlopen(req)
            except urllib2.URLError, e:
                xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
                return False
          else:
            xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
            return False


        response.read()
        response.close()

        return True

    #
    # returns a list of spreadsheets contained in the Google Docs account
    #
项目:Python-GoogleDrive-VideoStream    作者:ddurdle    | 项目源码 | 文件源码
def createHeaderRow(self,url):

        header = { 'User-Agent' : self.user_agent, 'Authorization' : 'GoogleLogin auth=%s' % self.authorization.getToken('wise'), 'GData-Version' : '3.0',  "If-Match" : '*', 'Content-Type': 'application/atom+xml'}

        entry = '<?xml version=\'1.0\' encoding=\'UTF-8\'?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended"> <gsx:hours>1</gsx:hours></entry>'

        req = urllib2.Request(url, entry, header)

        try:
            response = urllib2.urlopen(req)
        except urllib2.URLError, e:
          if e.code == 403 or e.code == 401:
            self.service.refreshToken()
            header = { 'User-Agent' : self.user_agent, 'Authorization' : 'GoogleLogin auth=%s' % self.authorization.getToken('wise'), 'GData-Version' : '3.0',  "If-Match" : '*', 'Content-Type': 'application/atom+xml'}
            req = urllib2.Request(url, entry, header)
            try:
                response = urllib2.urlopen(req)
            except urllib2.URLError, e:
                xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
                return False
          else:
            xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
            return False

        response.read()
        response.close()

        return True

    #
    # returns a list of worksheets with a link to their listfeeds
    #
项目:plugin.video.auvio    作者:rickybiscus    | 项目源码 | 文件源码
def log_error(self, message):
        """
        Add ERROR message to the Kodi log

        :param message: message to write to the Kodi log
        :type message: str
        """
        self.log(message, xbmc.LOGERROR)
项目:script.module.python.twitch    作者:MrSprigster    | 项目源码 | 文件源码
def error(self, message):
        message = prep_log_message(message)
        if xbmc:
            self._log(message, xbmc.LOGERROR)
        else:
            self._log.error(message)
项目:forthelulz    作者:munchycool    | 项目源码 | 文件源码
def showError(addonId, errorMessage):
    """
    Shows an error to the user and logs it

    Parameters:
    addonId: the current addon id
    message: the message to be shown
    """
    notify(addonId, errorMessage)
    xbmc.log(errorMessage, xbmc.LOGERROR)
项目:plugin.video.brplay    作者:olavopeixoto    | 项目源码 | 文件源码
def log_error(msg):
    if is_standalone:
        print msg
    else:
        xbmc.log(msg, level=xbmc.LOGERROR)
项目:plugin.video.brplay    作者:olavopeixoto    | 项目源码 | 文件源码
def log_error(msg):
    if is_standalone:
        print msg
    else:
        xbmc.log(msg, level=xbmc.LOGERROR)
项目:plugin.kogumi    作者:XIAZY    | 项目源码 | 文件源码
def emit(self, record):
        levels = {
            logging.CRITICAL: xbmc.LOGFATAL,
            logging.ERROR: xbmc.LOGERROR,
            logging.WARNING: xbmc.LOGWARNING,
            logging.INFO: xbmc.LOGINFO,
            logging.DEBUG: xbmc.LOGDEBUG,
            logging.NOTSET: xbmc.LOGNONE,
        }
        if get_setting_as_bool('debug'):
            try:
                xbmc.log(self.format(record), levels[record.levelno])
            except UnicodeEncodeError:
                xbmc.log(self.format(record).encode(
                    'utf-8', 'ignore'), levels[record.levelno])
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def add_list_items(self, items, content=None, end=True, withNextPage=False):
        if content:
            xbmcplugin.setContent(plugin.handle, content)
        list_items = []
        for item in items:
            if isinstance(item, Category):
                category_items = item.getListItems()
                for url, li, isFolder in category_items:
                    if url and li:
                        list_items.append((url, li, isFolder))
            elif isinstance(item, BrowsableMedia):
                url, li, isFolder = item.getListItem()
                if url and li:
                    list_items.append((url, li, isFolder))
        if withNextPage and len(items) > 0:
            # Add folder for next page
            try:
                totalNumberOfItems = items[0]._totalNumberOfItems
                nextOffset = items[0]._offset + self._config.pageSize
                if nextOffset < totalNumberOfItems and len(items) >= self._config.pageSize:
                    path = urlsplit(sys.argv[0]).path or '/'
                    path = path.split('/')[:-1]
                    path.append(str(nextOffset))
                    url = '/'.join(path)
                    self.add_directory_item(_T(30244).format(pos1=nextOffset, pos2=min(nextOffset+self._config.pageSize, totalNumberOfItems)), plugin.url_for_path(url))
            except:
                log('Next Page for URL %s not set' % sys.argv[0], xbmc.LOGERROR)
        if len(list_items) > 0:
            xbmcplugin.addDirectoryItems(plugin.handle, list_items)
        if end:
            xbmcplugin.endOfDirectory(plugin.handle)
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def __init__(self, pluginName, detailLevel=0, enableTidalApiLog=False):
        ''' Initialize Error Logging with a given Log Level
            detailLevel = 0 : xbmc.LOGERROR and xbmc.LOGNOTICE
            detailLevel = 1 : as level 0 plus xbmc.LOGWARNING
            detailLevel = 2 : as level 1 plus xbmc.LOGDEBUG
            detailLevel = 3 : as level 2 plus xbmc.LOGSEVERE
        '''
        self.pluginName = pluginName
        self.detailLevel = detailLevel
        self.debugServer = 'localhost'
        # Set Log Handler for tidalapi
        self.addTidalapiLogger(pluginName, enableDebug=enableTidalApiLog)
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def logException(self, e, txt=''):
        ''' Logs an Exception as Error Message '''
        try:
            if txt:
                if isinstance(txt, unicode):
                    txt = unidecode(txt)
                xbmc.log(b"[%s] %s\n%s" % (self.pluginName, txt, str(e)), level=xbmc.LOGERROR) 
            logging.exception(str(e))
        except:
            pass
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def user_playlist_clear(playlist_id):
    dialog = xbmcgui.Dialog()
    playlist = session.get_playlist(playlist_id)
    ok = dialog.yesno(_T(30258), _T(30259).format(name=playlist.title, count=playlist.numberOfItems))
    if ok:
        xbmc.executebuiltin('ActivateWindow(busydialog)')
        try:
            session.user.remove_all_playlist_entries(playlist_id)
        except Exception, e:
            log(str(e), level=xbmc.LOGERROR)
            traceback.print_exc()
        xbmc.executebuiltin('Dialog.Close(busydialog)')
        xbmc.executebuiltin('Container.Refresh()')
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def user_playlist_add_item(item_type, item_id):
    if item_type == 'playlist':
        srcPlaylist = session.get_playlist(item_id)
        if not srcPlaylist:
            return
        items = session.get_playlist_items(playlist=srcPlaylist)
        # Sort Items by Artist, Title
        sortMode = 'ALBUM' if ALBUM_PLAYLIST_TAG in srcPlaylist.description else 'LABEL'
        items.sort(key=lambda line: line.getSortText(mode=sortMode).upper(), reverse=False)
        items = ['%s' % item.id for item in items]
    elif item_type.startswith('album'):
        # Add First Track of the Album
        tracks = session.get_album_items(item_id)
        for track in tracks:
            if track.available:
                item_id = track.id
                break
        items = ['%s' % item_id]
    else:
        items = [item_id]
    playlist = session.user.selectPlaylistDialog(allowNew=True)
    if playlist:
        xbmc.executebuiltin('ActivateWindow(busydialog)')
        try:
            session.user.add_playlist_entries(playlist=playlist, item_ids=items)
        except Exception, e:
            log(str(e), level=xbmc.LOGERROR)
            traceback.print_exc()
        xbmc.executebuiltin('Dialog.Close(busydialog)')
        xbmc.executebuiltin('Container.Refresh()')
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def user_playlist_remove_item(playlist_id, entry_no):
    item_no = int('0%s' % entry_no) + 1
    playlist = session.get_playlist(playlist_id)
    ok = xbmcgui.Dialog().yesno(_T(30247) % playlist.title, _T(30241) % item_no)
    if ok:
        xbmc.executebuiltin('ActivateWindow(busydialog)')
        try:
            session.user.remove_playlist_entry(playlist, entry_no=entry_no)
        except Exception, e:
            log(str(e), level=xbmc.LOGERROR)
            traceback.print_exc()
        xbmc.executebuiltin('Dialog.Close(busydialog)')
        xbmc.executebuiltin('Container.Refresh()')
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def user_playlist_remove_id(playlist_id, item_id):
    playlist = session.get_playlist(playlist_id)
    ok = xbmcgui.Dialog().yesno(_T(30247) % playlist.title, _T(30246))
    if ok:
        xbmc.executebuiltin('ActivateWindow(busydialog)')
        try:
            session.user.remove_playlist_entry(playlist, item_id=item_id)
        except Exception, e:
            log(str(e), level=xbmc.LOGERROR)
            traceback.print_exc()
        xbmc.executebuiltin('Dialog.Close(busydialog)')
        xbmc.executebuiltin('Container.Refresh()')
项目:emulator.tools.retroarch    作者:JoKeRzBoX    | 项目源码 | 文件源码
def showError(addonId, errorMessage):
    """
    Shows an error to the user and logs it

    Parameters:
    addonId: the current addon id
    message: the message to be shown
    """
    notify(addonId, errorMessage)
    xbmc.log(errorMessage, xbmc.LOGERROR)
项目:script.tvguide.fullscreen    作者:primaeval    | 项目源码 | 文件源码
def getControl(self, controlId):
        if not controlId:
            return None
        try:
            return super(TVGuide, self).getControl(controlId)
        except Exception as detail:
            #log(traceback.print_stack())
            #xbmc.log("EXCEPTION: (script.tvguide.fullscreen) TVGuide.getControl %s" % detail, xbmc.LOGERROR)
            if controlId in self.ignoreMissingControlIds:
                return None
            if not self.isClosing:
                self.close()
            return None
项目:script.tvguide.fullscreen    作者:primaeval    | 项目源码 | 文件源码
def eventLoop(self):
        print 'Database.eventLoop() >>>>>>>>>> starting...'
        while True:
            self.event.wait()
            self.event.clear()

            event = self.eventQueue.pop(0)

            command = event[0]
            callback = event[1]

            print 'Database.eventLoop() >>>>>>>>>> processing command: ' + command.__name__

            try:
                result = command(*event[2:])
                self.eventResults[command.__name__] = result

                if callback:
                    if self._initialize == command:
                        threading.Thread(name='Database callback', target=callback, args=[result]).start()
                    else:
                        threading.Thread(name='Database callback', target=callback).start()

                if self._close == command:
                    del self.eventQueue[:]
                    break

            except Exception as detail:
                xbmc.log('Database.eventLoop() >>>>>>>>>> exception! %s = %s' % (detail,command.__name__), xbmc.LOGERROR)
                xbmc.executebuiltin("ActivateWindow(Home)")

        print 'Database.eventLoop() >>>>>>>>>> exiting...'
项目:plugin.video.streamlink    作者:beardypig    | 项目源码 | 文件源码
def log_error(self, message):
        """
        Add ERROR message to the Kodi log

        :param message: message to write to the Kodi log
        :type message: str
        """
        self.log(message, xbmc.LOGERROR)
项目:service.subtitles.brokensubs    作者:iamninja    | 项目源码 | 文件源码
def emit(self, record):
        levels = {
            logging.CRITICAL: xbmc.LOGFATAL,
            logging.ERROR: xbmc.LOGERROR,
            logging.WARNING: xbmc.LOGWARNING,
            logging.INFO: xbmc.LOGINFO,
            logging.DEBUG: xbmc.LOGDEBUG,
            logging.NOTSET: xbmc.LOGNONE,
        }
        if get_setting_as_bool('debug'):
            try:
                xbmc.log(self.format(record), levels[record.levelno])
            except UnicodeEncodeError:
                xbmc.log(self.format(record).encode(
                    'utf-8', 'ignore'), levels[record.levelno])
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def error(texto=""):
    texto = "    [" + get_caller() + "] " + encode_log(texto)

    xbmc.log("######## ERROR #########", xbmc.LOGERROR)
    xbmc.log(texto, xbmc.LOGERROR)
项目:plugin.video.skystreaming    作者:Ideneal    | 项目源码 | 文件源码
def log(msg):
    """log a message"""
    xbmc.log('SKYSTREAMING: %s' % msg, xbmc.LOGERROR)