Python xbmc 模块,log() 实例源码

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

项目:plugin.video.exodus    作者:lastship    | 项目源码 | 文件源码
def log(msg, level=LOGDEBUG):
    req_level = level
    # override message level to force logging when addon logging turned on
    if control.setting('addon_debug') == 'true' and level == LOGDEBUG:
        level = LOGNOTICE

    try:
        if isinstance(msg, unicode):
            msg = '%s (ENCODED)' % (msg.encode('utf-8'))

        xbmc.log('[%s] %s' % (name, msg), level)

    except Exception as e:
        try:
            xbmc.log('Logging Failure: %s' % (e), level)
        except:
            pass  # just give up
项目:plugin.video.exodus    作者:lastship    | 项目源码 | 文件源码
def profile(self, f):
        def method_profile_on(*args, **kwargs):
            try:
                self._profiler.enable()
                result = self._profiler.runcall(f, *args, **kwargs)
                self._profiler.disable()
                return result
            except Exception as e:
                log('Profiler Error: %s' % (e), LOGWARNING)
                return f(*args, **kwargs)

        def method_profile_off(*args, **kwargs):
            return f(*args, **kwargs)

        if _is_debugging():
            return method_profile_on
        else:
            return method_profile_off
项目:screensaver.kaster    作者:enen92    | 项目源码 | 文件源码
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
项目: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)
项目:Python-GoogleDrive-VideoStream    作者:ddurdle    | 项目源码 | 文件源码
def next(self):

#            log('video ' + str(episodes[self.current][CONSTANTS.D_SOURCE]) + ',' + str(episodes[self.current][CONSTANTS.D_SHOW]))

#        addVideo('plugin://plugin.video.gdrive?mode=playvideo&title='+episodes[video][0],
#                             { 'title' : str(episodes[video][CONSTANTS.D_SHOW]) + ' - S' + str(episodes[video][CONSTANTS.D_SEASON]) + 'xE' + str(episodes[video][CONSTANTS.D_EPISODE]) + ' ' + str(episodes[video][CONSTANTS.D_PART])  , 'plot' : episodes[video][CONSTANTS.D_SHOW] },
#                             img='None')
        # play video
#            if self.isExit == 0:
                self.play('plugin://plugin.video.gdrive-testing/?mode=video&instance='+str(self.service.instanceName)+'&title='+self.content[self.current][0])
                #self.play('plugin://plugin.video.gdrive/?mode=video&instance='+str(self.service.instanceName)+'&title='+self.content[self.current][0])
#                self.play(self.content[self.current][0])

#                self.tvScheduler.setVideoWatched(self.worksheet, self.content[self.current][0])
#                self.tvScheduler.createRow(self.worksheet, '','','','')
                if self.current < len(self.content):
                    self.current += 1
                else:
                    self.current = 0
项目:Python-GoogleDrive-VideoStream    作者:ddurdle    | 项目源码 | 文件源码
def PlayStream(self, url, item, seek, startPlayback=True, package=None):

        self.currentURL = url
        if startPlayback:
            self.play(url, item)
            if self.service.settings:
                xbmc.log(self.service.addon.getAddonInfo('name') + ': Playback url ' + str(url), xbmc.LOGNOTICE)

        if package is not None:
            self.package = package

        if seek != '':
            self.seek = float(seek)
            if self.service.settings:
                xbmc.log(self.service.addon.getAddonInfo('name') + ': Seek ' + str(seek), xbmc.LOGNOTICE)

#        self.tvScheduler.setVideoWatched(self.worksheet, self.content[self.current][0])
#        if seek > 0 and seek !='':
#            while not self.isPlaying(): #<== The should be    while self.isPlaying():
#                xbmc.sleep(500)
#            xbmc.sleep(2000)
#            self.time = float(seek)
#            self.seekTime(float(seek))
项目:script.matchcenter    作者:enen92    | 项目源码 | 文件源码
def onInit(self):
        xbmc.log(msg="[Match Center] Script started", level=xbmc.LOGDEBUG)
        if os.path.exists(ignored_league_list_file):
            self.ignored_leagues = [league.lower() for league in eval(FileIO.fileread(ignored_league_list_file)) if league] 
        else:
            self.ignored_leagues = []
        xbmc.executebuiltin("ClearProperty(no-games,Home)")
        self.getControl(32540).setImage(os.path.join(addon_path,"resources","img","goal.png"))
        xbmc.executebuiltin("SetProperty(loading-script-matchcenter-livescores,1,home)")
        self.livescoresThread()
        xbmc.executebuiltin("ClearProperty(loading-script-matchcenter-livescores,Home)")
        i = 0
        while self.isRunning:
            if (float(i*200)/(livescores_update_time*60*1000)).is_integer() and ((i*200)/(3*60*1000)) != 0:
                self.livescoresThread()
            xbmc.sleep(200)
            i += 1
        xbmc.log(msg="[Match Center] Script stopped", level=xbmc.LOGDEBUG)
项目:plugin.video.telekom-sport    作者:asciidisco    | 项目源码 | 文件源码
def use_inputstream(self):
        """
        Determines if inoutstream can/should be used to play the videos

        Note: At least Kodi 17.4 & Inoutstream 2.0.7 are needed, because
        of HSL support

        :returns:  bool - Use inputstream to play videos
        """
        raw_setting = self.get_addon().getSetting('use_inputstream')
        if raw_setting == 'false':
            return False
        kodi_version = int(self.get_kodi_version())
        inputstream_version_raw = self.get_inputstream_version()
        inputstream_version = int(inputstream_version_raw.replace('.', ''))
        if inputstream_version < 999:
            inputstream_version = inputstream_version * 10
        self.log('Kodi Version: ' + str(kodi_version))
        self.log('Inputstream Version: ' + str(inputstream_version))
        # determine if we can use inputstream for HLS
        use_inputstream = False
        if kodi_version >= 17 and inputstream_version >= 2070:
            use_inputstream = True
        return use_inputstream
项目:plugin.video.lastship    作者:lastship    | 项目源码 | 文件源码
def log(msg, level=LOGDEBUG):
    req_level = level
    # override message level to force logging when addon logging turned on
    if control.setting('addon_debug') == 'true' and level == LOGDEBUG:
        level = LOGNOTICE

    try:
        if isinstance(msg, unicode):
            msg = '%s (ENCODED)' % (msg.encode('utf-8'))

        xbmc.log('[%s] %s' % (name, msg), level)

    except Exception as e:
        try:
            xbmc.log('Logging Failure: %s' % (e), level)
        except:
            pass  # just give up
项目:plugin.video.lastship    作者:lastship    | 项目源码 | 文件源码
def profile(self, f):
        def method_profile_on(*args, **kwargs):
            try:
                self._profiler.enable()
                result = self._profiler.runcall(f, *args, **kwargs)
                self._profiler.disable()
                return result
            except Exception as e:
                log('Profiler Error: %s' % (e), LOGWARNING)
                return f(*args, **kwargs)

        def method_profile_off(*args, **kwargs):
            return f(*args, **kwargs)

        if _is_debugging():
            return method_profile_on
        else:
            return method_profile_off
项目:plugin.video.exodus    作者:huberyhe    | 项目源码 | 文件源码
def log(msg, level=LOGDEBUG):
    req_level = level
    # override message level to force logging when addon logging turned on
    if control.setting('addon_debug') == 'true' and level == LOGDEBUG:
        level = LOGNOTICE

    try:
        if isinstance(msg, unicode):
            msg = '%s (ENCODED)' % (msg.encode('utf-8'))

        xbmc.log('[%s] %s' % (name, msg), level)

    except Exception as e:
        try:
            xbmc.log('Logging Failure: %s' % (e), level)
        except:
            pass  # just give up
项目:plugin.video.exodus    作者:huberyhe    | 项目源码 | 文件源码
def profile(self, f):
        def method_profile_on(*args, **kwargs):
            try:
                self._profiler.enable()
                result = self._profiler.runcall(f, *args, **kwargs)
                self._profiler.disable()
                return result
            except Exception as e:
                log('Profiler Error: %s' % (e), LOGWARNING)
                return f(*args, **kwargs)

        def method_profile_off(*args, **kwargs):
            return f(*args, **kwargs)

        if _is_debugging():
            return method_profile_on
        else:
            return method_profile_off
项目:plugin.video.brplay    作者:olavopeixoto    | 项目源码 | 文件源码
def find_bandwidth_index(playlist, average_download_speed):
    if not playlist.is_variant:
        return 0

    bandwidth_options = []
    for index, playlist_item in enumerate(playlist.playlists):
        bandwidth_options.append({
            'index': index,
            'bandwidth': float(playlist.playlists[index].stream_info.bandwidth)
        })
    bandwidth_options = sorted(bandwidth_options, key=lambda k: int(k['bandwidth']), reverse=True)

    for bandwidth_option in bandwidth_options:
        if bandwidth_option['bandwidth'] < average_download_speed:
            log("SELECTED BANDWIDTH: %s" % bandwidth_option['bandwidth'])
            return bandwidth_option['index']

    return 0
项目:plugin.video.brplay    作者:olavopeixoto    | 项目源码 | 文件源码
def __download_segments_parallel(self, segments):
        threads = []
        for segment in segments:

            if self.g_stopEvent.isSet():
                return

            segment_number = self.__get_segment_number(segment.absolute_uri)

            if str(segment_number) in self.media_buffer or int(self.requested_segment) > int(segment_number):
                log("SKIPPING SEGMENT %s" % segment_number)
                continue

            worker = workers.Thread(self.__download_single_segment, segment)
            worker.daemon = True
            threads.append(worker)

        [i.start() for i in threads]
        [i.join() for i in threads]
项目:plugin.video.brplay    作者:olavopeixoto    | 项目源码 | 文件源码
def download_binary(self, url, dest_stream):

        log('DOWNLOADING BINARY URI: %s' % url)

        # current_bandwidth_index = self.find_bandwidth_index(self.manifest_playlist,
        #                                                     min(self.maxbitrate, self.average_download_speed))
        # self.selected_bandwidth_index = current_bandwidth_index
        # playlist = self.manifest_playlist.playlists[self.selected_bandwidth_index]
        # self.media_list = self.load_playlist_from_uri(playlist.absolute_uri)

        file = url.split('/')[-1]
        keys = filter(lambda k: k.uri.split('/')[-1] == file, self.media_list.keys)

        if len(keys) <= 0:
            log("ERROR: KEY NOT FOUND: %s | PLAYLIST: %s" % (file, self.media_list.dumps()))
            raise Exception("KEY NOT FOUND: %s" % file)

        self.key = keys[0]
        absolute_uri = self.key.absolute_uri

        log('DOWNLOADING BINARY ABSOLUTE URI: %s' % absolute_uri)

        for chunk in self.__download_chunks(absolute_uri):
            self.__send_back(chunk, dest_stream)
项目:plugin.video.brplay    作者:olavopeixoto    | 项目源码 | 文件源码
def __find_bandwidth_index(self, playlist, average_download_speed, safe_ratio=1.0):
        if not playlist.is_variant:
            return 0

        bandwidth_options = []
        for index, playlist_item in enumerate(playlist.playlists):
            bandwidth_options.append({
                'index': index,
                'bandwidth': float(playlist.playlists[index].stream_info.bandwidth)
            })
        bandwidth_options = sorted(bandwidth_options, key=lambda k: int(k['bandwidth']), reverse=True)

        for bandwidth_option in bandwidth_options:
            if bandwidth_option['bandwidth'] * safe_ratio < average_download_speed:
                log("SELECTED BANDWIDTH: %s" % bandwidth_option['bandwidth'])
                return bandwidth_option['index']

        return 0
项目:plugin.video.brplay    作者:olavopeixoto    | 项目源码 | 文件源码
def __download_segment_media_from_buffer(self, segment_uri, stream):
        if self.g_stopEvent and self.g_stopEvent.isSet():
            return

        segment_number = self.__get_segment_number(segment_uri)

        self.requested_segment = segment_number

        if str(segment_number) not in self.media_buffer:
            self.average_download_speed = 0
            log("SEGMENT %s NOT READY..." % str(segment_number))
            return False

        log("LOADING SEGMENT %s FROM BUFFER! :-)" % str(segment_number))

        segment_bytes = self.media_buffer[str(segment_number)]

        self.media_buffer[str(segment_number)] = None

        self.__send_back(segment_bytes, stream)

        return True
项目:plugin.video.brplay    作者:olavopeixoto    | 项目源码 | 文件源码
def is_inputstream_available():
    global __inputstream_addon_available

    if __inputstream_addon_available is None:
        lock = threading.RLock()

        try:
            lock.acquire()
            if __inputstream_addon_available is None:
                (inputstream_addon, inputstream_enabled) = get_inputstream_addon()
                __inputstream_addon_available = inputstream_addon is not None and inputstream_enabled
        except Exception as ex:
            log("ERROR FINDING INPUTSTREAM ADDON, CONSIDERING MISSING: %s" % repr(ex))
            __inputstream_addon_available = False
        finally:
            lock.release()

    return __inputstream_addon_available
项目:plugin.video.stream-cinema    作者:bbaronSVK    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        try:
            self.log("[SC] player 1")
            self.estimateFinishTime = '00:00:00'
            self.realFinishTime = '00:00:00'
            self.itemDuration = 0
            self.watchedTime = 0
            self.win = xbmcgui.Window(10000)
            self.scid = None
            self.ids = None
            self.itemDBID = None
            self.itemType = None
            self.parent = kwargs.get('parent')
            self.se = None
            self.ep = None
            self.popup = None
            self.thread = None
            self.stream = None
            self.upNextEnable = True
            self.libItem = None
        except Exception:
            self.log("SC Chyba MyPlayer: %s" % str(traceback.format_exc()))
项目: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])
项目:specto    作者:mrknow    | 项目源码 | 文件源码
def addMenuItem(self, name, iconImage=None, folder=True, menu=True, **kwargs):
        """Add one submenu item to the list. [internal]"""
        if not iconImage:
            iconImage = 'DefaultAddonsSearch.png'
        # general menu item
        # liz = xbmcgui.ListItem(title, iconImage="DefaultFolder.png", thumbnailImage=iconImage)
        # liz.setInfo(type="Video", infoLabels={"Title": title})
        url = self.buildPluginUrl(name=name, **kwargs)
        xbmc.log('SEARCH: create menu item %s, query:"%s", url:"%s"' % (name, kwargs.get('query'), url))
        li = xbmcgui.ListItem(kwargs.get('title', ''), iconImage="DefaultFolder.png", thumbnailImage=iconImage)
        li.addContextMenuItems([
            (_('Remove'), 'RunPlugin(%s)' % (url + '&action=remove')),
            (_('Rename'), 'RunPlugin(%s)' % (url + '&action=rename')),
            (_('Clean'),  'RunPlugin(%s)' % (url + '&action=clean')),
        ])
        xbmcplugin.addDirectoryItem(handle=self._addonHandle, url=url, listitem=li, isFolder=folder)
项目:specto    作者:mrknow    | 项目源码 | 文件源码
def listSearch(self, text):
        """Create list of found movies. [interal]"""
        if text is None:
            return True
        if not self.url:
            return text
        q = urllib.quote_plus(text)
        if '%s' in self.url:
            # shortcut, just URL with simple "%s" for quoted query
            url = self.url % q
        else:
            # full format URL with "%(quoted)s" for quoted query
            # and "%(text)s" for unquoted query
            url = self.url % (dict(q=q, quoted=q, text=text))
        if self.listItemsFun:
            xbmc.log('SEARCH: searching "%s"' % url)
            self.listItemsFun(url)
        return url
项目:specto    作者:mrknow    | 项目源码 | 文件源码
def __init__(self):
        self.getSettings()
        files = self.getFiles()
        for item in files:
            filetype = item[0]
            if filetype == 'log':
                error = LANGUAGE(32011)
                name = LANGUAGE(32031)
            elif filetype == 'oldlog':
                error = LANGUAGE(32012)
                name = LANGUAGE(32032)
            succes, data = self.readLog(item[1])
            if succes:
                content = self.cleanLog(data)
                succes, result = self.postLog(content)
                if succes:
                    self.showResult(LANGUAGE(32005) % (name, result))
                else:
                    self.showResult('%s[CR]%s' % (error, result))
            else:
                self.showResult('%s[CR]%s' % (error, result))
项目: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")
项目:script.tvguide.fullscreen    作者:primaeval    | 项目源码 | 文件源码
def connectToValidated(self, connection, wait):
        # Given the number of a validated connection, connect to it.  Return True when the connection has happened 
        # or False if there's a problem connecting (or there's not a VPN connection available for this connection 
        # number).  Return True without messing with the connection if the current VPN is the same as the VPN being
        # requested.  The wait parameter will determine if the function returns once the connection has been made, 
        # or if it's fire and forget (in which case True will be returned regardless)
        if not self.isVPNSetUp(): return False
        if connection < 1 or connection > 10: return False
        connection = connection - 1
        self.refreshLists()
        if self.primary_vpns[connection] == "": return False
        if self.getConnected() == self.primary_vpns[connection]: return True
        xbmc.log(msg="VPN Mgr API : Connecting to " + self.primary_vpns[connection], level=xbmc.LOGDEBUG)
        self.setAPICommand(self.primary_vpns[connection])
        if wait: return self.waitForConnection(self.primary_vpns[connection])
        return True
项目:script.tvguide.fullscreen    作者:primaeval    | 项目源码 | 文件源码
def deleteDB():
    try:
        xbmc.log("[script.tvguide.fullscreen] Deleting database...", xbmc.LOGDEBUG)
        dbPath = xbmc.translatePath(xbmcaddon.Addon(id = 'script.tvguide.fullscreen').getAddonInfo('profile'))
        dbPath = os.path.join(dbPath, 'source.db')

        delete_file(dbPath)

        passed = not os.path.exists(dbPath)

        if passed:
            xbmc.log("[script.tvguide.fullscreen] Deleting database...PASSED", xbmc.LOGDEBUG)
        else:
            xbmc.log("[script.tvguide.fullscreen] Deleting database...FAILED", xbmc.LOGDEBUG)

        return passed

    except Exception, e:
        xbmc.log('[script.tvguide.fullscreen] Deleting database...EXCEPTION', xbmc.LOGDEBUG)
        return False
项目:script.tvguide.fullscreen    作者:primaeval    | 项目源码 | 文件源码
def onCachesUpdated(self):
        #BUG doesn't work on login (maybe always?)
        if ADDON.getSetting('notifications.enabled') == 'true':
            n = notification.Notification(self.database, ADDON.getAddonInfo('path'))
            #n.scheduleNotifications()
        if ADDON.getSetting('autoplays.enabled') == 'true':
            n = autoplay.Autoplay(self.database, ADDON.getAddonInfo('path'))
            #n.scheduleAutoplays()
        if ADDON.getSetting('autoplaywiths.enabled') == 'true':
            n = autoplaywith.Autoplaywith(self.database, ADDON.getAddonInfo('path'))
            #n.scheduleAutoplaywiths()
        self.database.close(None)
        xbmc.log("[script.tvguide.fullscreen] Background Update Finished", xbmc.LOGNOTICE)
        if ADDON.getSetting('background.notify') == 'true':
            d = xbmcgui.Dialog()
            d.notification("TV Guide Fullscreen", "Finished Updating")
项目:script.tvguide.fullscreen    作者:primaeval    | 项目源码 | 文件源码
def __init__(self, addon, force):
        self.needReset = False
        self.fetchError = False
        self.start = True
        self.force = force
        '''
        self.xmltvInterval = int(addon.getSetting('sd.interval'))
        self.logoSource = int(addon.getSetting('logos.source'))
        self.addonsType = int(addon.getSetting('addons.ini.type'))

        # make sure the folder in the user's profile exists or create it!
        if not os.path.exists(self.PLUGIN_DATA):
            os.makedirs(self.PLUGIN_DATA)

        # make sure the ini file is fetched as well if necessary
        if self.addonsType != self.INI_TYPE_DEFAULT:
            customFile = str(addon.getSetting('addons.ini.file'))
            if os.path.exists(customFile):
                # uses local file provided by user!
                xbmc.log('[%s] Use local file: %s' % (ADDON.getAddonInfo('id'), customFile), xbmc.LOGDEBUG)
            else:
                # Probably a remote file
                xbmc.log('[%s] Use remote file: %s' % (ADDON.getAddonInfo('id'), customFile), xbmc.LOGDEBUG)
                self.updateLocalFile(customFile, addon, True, force=force)
        '''
项目:google-photos-for-kodi    作者:nkanand4    | 项目源码 | 文件源码
def make_request(req, tok, data=None):
    xbmc.log('Attempting request')
    req.add_header('Authorization', 'Bearer ' + tok['access_token'])
    try:
        resp_stream = urllib2.urlopen(req, data)
        res = resp_stream.read()
        xbmc.log('Response successfully acquired')
        return res
    except urllib2.HTTPError, e:
        xbmc.log('Error while making request')
        if e.code == 401:
            tok = get_access_token_using_refresh_token(tok)
            res = make_request(req, tok)
            return res
        elif e.code == 403:
            get_user_code_for_device()
            return ""
项目:plugin.video.exodus    作者:lastship    | 项目源码 | 文件源码
def trace(method):
    def method_trace_on(*args, **kwargs):
        start = time.time()
        result = method(*args, **kwargs)
        end = time.time()
        log('{name!r} time: {time:2.4f}s args: |{args!r}| kwargs: |{kwargs!r}|'.format(name=method.__name__, time=end - start, args=args, kwargs=kwargs), LOGDEBUG)
        return result

    def method_trace_off(*args, **kwargs):
        return method(*args, **kwargs)

    if _is_debugging():
        return method_trace_on
    else:
        return method_trace_off
项目:screensaver.kaster    作者:enen92    | 项目源码 | 文件源码
def log(message,level):
    prefix = b"[%s] " % ADDON_ID
    formatter = prefix + b'%(name)s: %(message)s'
    try:
        xbmc.log(formatter, level)
    except UnicodeEncodeError:
        xbmc.log(formatter.encode(
            'utf-8', 'ignore'), level)
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def log_msg(msg, loglevel=xbmc.LOGDEBUG):
    '''log to kodi logfile'''
    if isinstance(msg, unicode):
        msg = msg.encode('utf-8')
    xbmc.log("Skin Helper Backup --> %s" % msg, level=loglevel)
项目: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
项目:service.subtitles.tusubtitulo    作者:josecurioso2    | 项目源码 | 文件源码
def log(module, msg):
    xbmc.log((u"### [%s] - %s" % (module,msg,)).encode('utf-8'), level=xbmc.LOGDEBUG)
项目:service.subtitles.tusubtitulo    作者:josecurioso2    | 项目源码 | 文件源码
def buildURL(tvshow, season, episode):
    episodeFetch = ""
    try:
        APIKey = "AIzaSyAm6QlezxEd4N2flR2QO6aVYQ3cx_K4xsw"
        googleCSE = "https://www.googleapis.com/customsearch/v1?key=" + APIKey + "&cx=" + CSX + "&fields=items(title,link)&q="; #separe spaces with +
        searchURL = googleCSE + tvshow.replace(" ", "+")

        page = urllib.urlopen(searchURL).read()
        data = json.loads(page)
        showIdWord = data["items"][0]["title"].strip().strip("TuSubtitulo").strip().strip("-").strip().replace(" ", "-")

        episodeFetch = "https://www.tusubtitulo.com/showsub.php?ushow=" + showIdWord.lower() + "&useason=" + str(season) + "&uepisode=" + str(episode)

    except:
        APIKey = "AIzaSyAdtBdgZnLvZAcskQVYZcMLSnPu57z4HGA"
        googleCSE = "https://www.googleapis.com/customsearch/v1?key=" + APIKey + "&cx=" + CSX + "&fields=items(title,link)&q="; #separe spaces with +
        searchURL = googleCSE + tvshow.replace(" ", "+")

        page = urllib.urlopen(searchURL).read()
        data = json.loads(page)
        showIdWord = data["items"][0]["title"].strip().strip("TuSubtitulo").strip().strip("-").strip().replace(" ", "-")

        episodeFetch = "https://www.tusubtitulo.com/showsub.php?ushow=" + showIdWord.lower() + "&useason=" + str(season) + "&uepisode=" + str(episode)


    log(__name__, "EpisodeLink %s" % episodeFetch)
    return episodeFetch
项目:service.subtitles.tusubtitulo    作者:josecurioso2    | 项目源码 | 文件源码
def clean_subtitles_list(subtitles_list):
    seen = set()
    subs = []
    for sub in subtitles_list:
        filename = sub['link']
        #log(__name__, "Filename: %s" % filename)
        if filename not in seen:
            subs.append(sub)
            seen.add(filename)
    return subs
项目: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)
项目:plugin.video.bdyun    作者:caasiu    | 项目源码 | 文件源码
def showNotification(title,message, time=4000):
    """Show Notification

    Args: 
        title: has to be unicode
        message: has to be unicode
        time: Time that the message is beeing displayed
    """
    __addoniconpath__ = os.path.join(addon_dir(),"icon.png")
    log(u'Notification. %s: %s' % (title, message) )
    xbmc.executebuiltin(encode('Notification("' + title + '","' + message + '",'+(str(time)).decode('utf-8')+',"' + __addoniconpath__ + '")'))
项目:konsodi    作者:kharts    | 项目源码 | 文件源码
def debug(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.LOGDEBUG)
项目: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 log_msg(msg, loglevel=xbmc.LOGDEBUG):
    '''log message to kodi log'''
    if isinstance(msg, unicode):
        msg = msg.encode('utf-8')
    if DEBUG and loglevel == xbmc.LOGDEBUG:
        loglevel = xbmc.LOGNOTICE
    xbmc.log("%s --> %s" % (ADDON_ID, msg), level=loglevel)
项目:plugin.audio.spotify    作者:marcelveldt    | 项目源码 | 文件源码
def log_exception(modulename, exceptiondetails):
    '''helper to properly log an exception'''
    log_msg(format_exc(sys.exc_info()), xbmc.LOGDEBUG)
    log_msg("Exception in %s ! --> %s" % (modulename, exceptiondetails), xbmc.LOGWARNING)
项目: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 playNext(self, service, package):
            (mediaURLs, package) = service.getPlaybackCall(package)

            options = []
            mediaURLs = sorted(mediaURLs)
            for mediaURL in mediaURLs:
                options.append(mediaURL.qualityDesc)
                if mediaURL.qualityDesc == 'original':
                    originalURL = mediaURL.url

            playbackURL = ''
            playbackQuality = ''
            if service.settings.promptQuality:
                if len(options) > 1:
                    ret = xbmcgui.Dialog().select(service.addon.getLocalizedString(30033), options)
                else:
                    ret = 0
            else:
                ret = 0

            playbackURL = mediaURLs[ret].url
            if self.service.settings:
                xbmc.log(self.service.addon.getAddonInfo('name') + ': Play next ' + str(playbackURL), xbmc.LOGNOTICE)

            playbackQuality = mediaURLs[ret].quality
            item = xbmcgui.ListItem(package.file.displayTitle(), iconImage=package.file.thumbnail,
                                thumbnailImage=package.file.thumbnail, path=playbackURL+'|' + service.getHeadersEncoded())
            item.setInfo( type="Video", infoLabels={ "Title": package.file.title } )
            self.PlayStream(playbackURL+'|' + service.getHeadersEncoded(),item,0,package)
项目:Python-GoogleDrive-VideoStream    作者:ddurdle    | 项目源码 | 文件源码
def playList(self, service):
        while self.current < len(self.mediaItems) and not self.isExit:
            self.playNext(service, self.mediaItems[self.current])
            current = self.current
            while current == self.current and not self.isExit:
                xbmc.sleep(3000)

        if self.service.settings:
            xbmc.log(self.service.addon.getAddonInfo('name') + ': Exit play list', xbmc.LOGNOTICE)

#    def onPlayBackSeek(self,offset):
项目: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 createRow(self,url, folderID, folderName, fileID, fileName):


#        header = { 'User-Agent' : self.user_agent, 'Authorization' : 'GoogleLogin auth=%s' % self.authorization.getToken('wise'), 'GData-Version' : '3.0',  'Content-Type': 'application/atom+xml'}
        header = { 'User-Agent' : self.user_agent, 'Authorization' : 'Bearer ' + self.service.authorization.getToken('auth_access_token'), '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:gsx="http://schemas.google.com/spreadsheets/2006/extended"> <gsx:source>S3E12 - The Red Dot.avi-0002</gsx:source><gsx:nfo>test.nfo</gsx:nfo><gsx:show>Seinfeld</gsx:show><gsx:season>3</gsx:season><gsx:episode>1</gsx:episode><gsx:part>1</gsx:part><gsx:watched>0</gsx:watched><gsx:duration>1</gsx:duration></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
    #