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

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

项目:catchup4kodi    作者:catchup4kodi    | 项目源码 | 文件源码
def XfinityInstaller():
    path = os.path.join(xbmc.translatePath('special://home'),'userdata', 'sources.xml')
    if not os.path.exists(path):
        f = open(path, mode='w')
        f.write('<sources><files><source><name>.[COLOR blue]X[/COLOR]finity Installer</name><path pathversion="1">http://xunitytalk.me/xfinity</path></source></files></sources>')
        f.close()
        return

    f   = open(path, mode='r')
    str = f.read()
    f.close()
    if not'xunitytalk.me/xfinity' in str:
        if '</files>' in str:
            str = str.replace('</files>','<source><name>.[COLOR blue]X[/COLOR]finity Installer</name><path pathversion="1">http://xunitytalk.me/xfinity</path></source></files>')
            f = open(path, mode='w')
            f.write(str)
            f.close()
        else:
            str = str.replace('</sources>','<files><source><name>.[COLOR blue]X[/COLOR]finity Installer</name><path pathversion="1">http://xunitytalk.me/xfinity</path></source></files></sources>')
            f = open(path, mode='w')
            f.write(str)
            f.close()
项目:screensaver.kaster    作者:enen92    | 项目源码 | 文件源码
def get_images(self, override=False):
        # Read google images from json file
        self.images = []
        if kodiutils.get_setting_as_int("screensaver-mode") == 0 or kodiutils.get_setting_as_int("screensaver-mode") == 2 or override:
            with open(IMAGE_FILE, "r") as f:
                images = f.read()
            self.images = json.loads(images)
        # Check if we have images to append
        if kodiutils.get_setting_as_int("screensaver-mode") == 1 or kodiutils.get_setting_as_int("screensaver-mode") == 2 and not override:
            if kodiutils.get_setting("my-pictures-folder") and xbmcvfs.exists(xbmc.translatePath(kodiutils.get_setting("my-pictures-folder"))):
                for image in screensaverutils.get_own_pictures(kodiutils.get_setting("my-pictures-folder")):
                    self.images.append(image)
            else:
                return self.get_images(override=True)
        shuffle(self.images)
        return
项目: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
项目:YoutubeTV    作者:dude56987    | 项目源码 | 文件源码
def saveFile(fileName,content):
    '''
    Save a file with the path fileName containing the content content.

    :return None
    '''
    # create the basepath using special protocol
    basePath=('special://userdata/addon_data/'+_id+'/')
    basePath=xbmc.translatePath(basePath)
    # if the base config directory does not exist
    if os.path.exists(basePath) is False:
        # create the base config path
        thumbnail=subprocess.Popen(['mkdir', '-p',basePath])
    # open the file to write
    fileObject=open((basePath+fileName),'w')
    # write file content
    fileObject.write(content)
    # close the file
    fileObject.close()
################################################################################
项目: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
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def backup_theme(self, themename):
        '''backup a colortheme to a zipfile'''
        import zipfile
        backup_path = xbmcgui.Dialog().browse(3, self.addon.getLocalizedString(32029), "files").decode("utf-8")
        if backup_path:
            xbmc.executebuiltin("ActivateWindow(busydialog)")
            backup_name = u"%s ColorTheme - %s" % (get_skin_name().capitalize(), themename)
            backupfile = os.path.join(backup_path, backup_name + u".zip")
            zip_temp = u'special://temp/%s.zip' % backup_name
            xbmcvfs.delete(zip_temp)
            xbmcvfs.delete(backupfile)
            zip_temp = xbmc.translatePath(zip_temp).decode("utf-8")
            zip_file = zipfile.ZipFile(zip_temp, "w", zipfile.ZIP_DEFLATED)
            abs_src = os.path.abspath(xbmc.translatePath(self.userthemes_path).decode("utf-8"))
            for filename in xbmcvfs.listdir(self.userthemes_path)[1]:
                if (filename.startswith("%s_" % themename) or
                        filename.replace(".theme", "").replace(".jpg", "") == themename):
                    filename = filename.decode("utf-8")
                    filepath = xbmc.translatePath(self.userthemes_path + filename).decode("utf-8")
                    absname = os.path.abspath(filepath)
                    arcname = absname[len(abs_src) + 1:]
                    zip_file.write(absname, arcname)
            zip_file.close()
            xbmcvfs.copy(zip_temp, backupfile)
            xbmc.executebuiltin("Dialog.Close(busydialog)")
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def add_tozip(src, zip_file, abs_src):
    '''helper method'''
    dirs, files = xbmcvfs.listdir(src)
    for filename in files:
        filename = filename.decode("utf-8")
        log_msg("zipping %s" % filename)
        filepath = xbmc.translatePath(os.path.join(src, filename)).decode("utf-8")
        absname = os.path.abspath(filepath)
        arcname = absname[len(abs_src) + 1:]
        try:
            # newer python can use unicode for the files in the zip
            zip_file.write(absname, arcname)
        except Exception:
            # older python version uses utf-8 for filenames in the zip
            zip_file.write(absname.encode("utf-8"), arcname.encode("utf-8"))
    for directory in dirs:
        add_tozip(os.path.join(src, directory), zip_file, abs_src)
    return zip_file
项目: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.")
项目:tvalacarta    作者:tvalacarta    | 项目源码 | 文件源码
def force_creation_advancedsettings(item):

    # Ruta del advancedsettings
    import xbmc,xbmcgui,os
    advancedsettings = xbmc.translatePath("special://userdata/advancedsettings.xml")

    # Copia el advancedsettings.xml desde el directorio resources al userdata
    fichero = open( os.path.join(config.get_runtime_path(),"resources","advancedsettings.xml") )
    texto = fichero.read()
    fichero.close()

    fichero = open(advancedsettings,"w")
    fichero.write(texto)
    fichero.close()

    dialog2 = xbmcgui.Dialog()
    dialog2.ok("plugin", "Se ha creado un fichero advancedsettings.xml","con la configuración óptima para el streaming.")

    return []
项目:plugin.video.stream-cinema    作者:bbaronSVK    | 项目源码 | 文件源码
def saveSubtitle(self, content, lang, convert=True):
        codePageDict = {'ara': 'cp1256', 'ar': 'cp1256', 'cs': 'cp1250', 'ell': 'cp1253', 
            'el': 'cp1253', 'heb': 'cp1255', 'he': 'cp1255', 'sk': 'cp1250', 'tur': 'cp1254', 
            'tr': 'cp1254', 'rus': 'cp1251', 'ru': 'cp1251'}

        subtitle = xbmc.validatePath(xbmc.translatePath('special://temp/'))
        subtitle = os.path.join(subtitle, 'AutomatickeTitulky.%s.srt' % lang)

        codepage = codePageDict.get(lang, '')
        if codepage and self.getSetting('subtitles.utf') == 'true':
            try:
                content_encoded = codecs.decode(content, codepage)
                content = codecs.encode(content_encoded, 'utf-8')
            except Exception, e:
                util.debug("[SC] chyba ukladania titulkov....")
                pass

        file = xbmcvfs.File(subtitle, 'w')
        file.write(str(content))
        file.close()
        return subtitle
项目: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 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 generate_settings_file(target_path):
    source_path = xbmc.translatePath(
        os.path.join(ADDON.getAddonInfo('path'), 'resources', 'settings.xml'))
    root_target = ceT.Element("settings")
    tree_source = eT.parse(source_path)
    root_source = tree_source.getroot()
    for item in root_source.findall('category'):
        for setting in item.findall('setting'):
            if 'id' in setting.attrib:
                value = ''
                if 'default' in setting.attrib:
                    value = setting.attrib['default']
                ceT.SubElement(root_target, 'setting', id=setting.attrib['id'], value=value)
    tree_target = ceT.ElementTree(root_target)
    f = open(target_path, 'w')
    tree_target.write(f)
    f.close()
项目:script.tvguide.fullscreen    作者:primaeval    | 项目源码 | 文件源码
def __init__(self,force=False):
        self.conn = None
        self.eventQueue = list()
        self.event = threading.Event()
        self.eventResults = dict()

        self.loadOptional(force)
        self.source = instantiateSource(force)

        self.updateInProgress = False
        self.updateFailed = False
        self.settingsChanged = None
        self.alreadyTriedUnlinking = False
        self.channelList = list()
        self.category = "Any"

        profilePath = xbmc.translatePath(ADDON.getAddonInfo('profile'))
        if not os.path.exists(profilePath):
            os.makedirs(profilePath)
        self.databasePath = os.path.join(profilePath, Database.SOURCE_DB)

        threading.Thread(name='Database Event Loop', target=self.eventLoop).start()
项目:script.tvguide.fullscreen    作者:primaeval    | 项目源码 | 文件源码
def autocrop_image(infile,outfile):
    infile = xbmc.translatePath(infile)
    image = Image.open(infile)
    border = 0
    size = image.size
    bb_image = image
    bbox = bb_image.getbbox()
    if (size[0] == bbox[2]) and (size[1] == bbox[3]):
        bb_image=bb_image.convert("RGB")
        bb_image = ImageOps.invert(bb_image)
        bbox = bb_image.getbbox()
    image = image.crop(bbox)
    (width, height) = image.size
    width += border * 2
    height += border * 2
    ratio = float(width)/height
    cropped_image = Image.new("RGBA", (width, height), (0,0,0,0))
    cropped_image.paste(image, (border, border))
    #TODO find epg height
    logo_height = 450 / int(ADDON.getSetting('channels.per.page'))
    logo_height = logo_height - 2
    cropped_image = cropped_image.resize((int(logo_height*ratio), logo_height),Image.ANTIALIAS)
    outfile = xbmc.translatePath(outfile)
    cropped_image.save(outfile)
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def verify_directories_created():
    from core import logger
    from core import filetools

    config_paths = [["librarypath",      "library"],
                    ["downloadpath",     "downloads"],
                    ["downloadlistpath", "downloads/list"],
                    ["settings_path",    "settings_channels"]]

    for path, default in config_paths:
        saved_path = get_setting(path)
        if not saved_path:
            saved_path = "special://profile/plugin_data/video/pelisalacarta/" + default
            set_setting(path, saved_path)

        saved_path = xbmc.translatePath(saved_path)
        if not filetools.exists(saved_path):
            logger.debug("Creating %s: %s" % (path, saved_path))
            filetools.mkdir(saved_path)

        # Biblioteca
        if path == "librarypath":
            set_setting("library_version", "v4")
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def __init__(self, url, mode = "r"):
        import random
        try:
          import xbmc
        except:
          xbmc = None
        self.url = url
        self.remote, self.share, self.path = path = connect(url)
        self.mode = mode
        self.binary = False
        self.canread = False
        self.canwrite = False
        self.closed = True
        self.size = 0
        self.pos = 0
        if xbmc:
          self.tmp_path = os.path.join(xbmc.translatePath("special://temp/"), "%08x" % (random.getrandbits(32)))
        else:
          self.tmp_path = os.path.join(os.getenv("TEMP") or os.getenv("TMP") or os.getenv("TMPDIR"), "%08x" % (random.getrandbits(32)))
        self.tmp_file = None

        self.__get_mode__()
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def onAction(self, action):
             if action == ACTION_SELECT_ITEM or action == ACTION_GESTURE_SWIPE_LEFT:
                import os
                import xbmc
                APPCOMMANDDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "customapp.xml")
                NOBACKDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "noback.xml")
                REMOTENOBACKDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "remotenoback.xml")
                APPNOBACKDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "appnoback.xml")
                TESTPYDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "test.py")
                try:
                    os.remove(NOBACKDESTFILE)
                    os.remove(REMOTENOBACKDESTFILE)
                    os.remove(APPNOBACKDESTFILE)
                    if os.path.exists ( TESTPYDESTFILE ):
                        urllib.urlretrieve ("https://raw.githubusercontent.com/neno1978/script.palc.forcerefresh/master/Bityouth/customapp.xml", APPCOMMANDDESTFILE )
                    xbmc.executebuiltin('Action(reloadkeymaps)')
                except:
                    xbmc.executebuiltin('Action(reloadkeymaps)')
                self.close()
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def onAction(self, action):
            if action == ACTION_SELECT_ITEM or action == ACTION_GESTURE_SWIPE_LEFT:
               import os
               import xbmc
               APPCOMMANDDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "customapp.xml")
               NOBACKDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "noback.xml")
               REMOTENOBACKDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "remotenoback.xml")
               APPNOBACKDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "appnoback.xml")
               TESTPYDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "test.py")
               try:
                  os.remove(NOBACKDESTFILE)
                  os.remove(REMOTENOBACKDESTFILE)
                  os.remove(APPNOBACKDESTFILE)
                  if os.path.exists ( TESTPYDESTFILE ):
                     urllib.urlretrieve ("https://raw.githubusercontent.com/neno1978/script.palc.forcerefresh/master/Bityouth/customapp.xml", APPCOMMANDDESTFILE )
                  xbmc.executebuiltin('Action(reloadkeymaps)')
               except:
                  xbmc.executebuiltin('Action(reloadkeymaps)')
               self.close()
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def onAction(self, action):
            if action == ACTION_SELECT_ITEM or action == ACTION_GESTURE_SWIPE_LEFT:
               ###Se vuelven a cargar Customkey al salir de info
               import os, sys
               import xbmc
               APPCOMMANDDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "customapp.xml")
               NOBACKDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "noback.xml")
               REMOTENOBACKDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "remotenoback.xml")
               APPNOBACKDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "appnoback.xml")
               TESTPYDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "test.py")
               try:
                   os.remove(NOBACKDESTFILE)
                   os.remove(REMOTENOBACKDESTFILE)
                   os.remove(APPNOBACKDESTFILE)
                   if os.path.exists ( TESTPYDESTFILE ):
                      urllib.urlretrieve ("https://raw.githubusercontent.com/neno1978/script.palc.forcerefresh/master/Bricocine/customapp.xml", APPCOMMANDDESTFILE )
                   xbmc.executebuiltin('Action(reloadkeymaps)')
               except:
                  pass
               self.close()
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def onAction(self, action):
            if action == ACTION_SELECT_ITEM or action == ACTION_GESTURE_SWIPE_LEFT:
               import os, sys
               import xbmc
               APPCOMMANDDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "customapp.xml")
               NOBACKDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "noback.xml")
               REMOTENOBACKDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "remotenoback.xml")
               APPNOBACKDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "appnoback.xml")
               TESTPYDESTFILE = os.path.join(xbmc.translatePath('special://userdata/keymaps'), "test.py")
               try:
                   os.remove(NOBACKDESTFILE)
                   os.remove(REMOTENOBACKDESTFILE)
                   os.remove(APPNOBACKDESTFILE)
                   xbmc.executebuiltin('Action(reloadkeymaps)')
                   if os.path.exists ( TESTPYDESTFILE ):
                      urllib.urlretrieve ("https://raw.githubusercontent.com/neno1978/script.palc.forcerefresh/master/Bricocine/customapp.xml", APPCOMMANDDESTFILE )
                   xbmc.executebuiltin('Action(reloadkeymaps)')
               except:
                   xbmc.executebuiltin('Action(reloadkeymaps)')
               self.close()
项目: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 refresh_image(imagepath):
    '''tell kodi texture cache to refresh a particular image'''
    import sqlite3
    dbpath = xbmc.translatePath("special://database/Textures13.db").decode('utf-8')
    connection = sqlite3.connect(dbpath, timeout=30, isolation_level=None)
    try:
        cache_image = connection.execute('SELECT cachedurl FROM texture WHERE url = ?', (imagepath,)).fetchone()
        if cache_image and isinstance(cache_image, (unicode, str)):
            if xbmcvfs.exists(cache_image):
                xbmcvfs.delete("special://profile/Thumbnails/%s" % cache_image)
            connection.execute('DELETE FROM texture WHERE url = ?', (imagepath,))
        connection.close()
    except Exception as exc:
        log_exception(__name__, exc)
    finally:
        del connection

# pylint: disable-msg=too-many-local-variables
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
def __init__(self, url, mode = "r"):
        import random
        try:
          import xbmc
        except:
          xbmc = None
        self.url = url
        self.remote, self.share, self.path = path = connect(url)
        self.mode = mode
        self.binary = False
        self.canread = False
        self.canwrite = False
        self.closed = True
        self.size = 0
        self.pos = 0
        if xbmc:
          self.tmp_path = os.path.join(xbmc.translatePath("special://temp/"), "%08x" % (random.getrandbits(32)))
        else:
          self.tmp_path = os.path.join(os.getenv("TEMP") or os.getenv("TMP") or os.getenv("TMPDIR"), "%08x" % (random.getrandbits(32)))
        self.tmp_file = None

        self.__get_mode__()
项目:plugin.video.amazon65    作者:phil65    | 项目源码 | 文件源码
def parseSubs(data):
    subs = []
    if addon.getSetting('subtitles') == 'false':
        return subs
    for sub in data:
        lang = sub['displayName'].split('(')[0].strip()
        common.Log('Convert %s Subtitle' % lang)
        file = xbmc.translatePath('special://temp/%s.srt' % lang).decode('utf-8')
        soup = BeautifulSoup(common.getURL(sub['url']))
        enc = soup.originalEncoding
        num = 0
        with codecs.open(file, 'w', encoding='utf-8') as srt:
            for caption in soup.findAll('tt:p'):
                num += 1
                subtext = caption.renderContents().decode(enc).replace('<tt:br>', '\n').replace('</tt:br>', '')
                srt.write(u'%s\n%s --> %s\n%s\n\n' % (num, caption['begin'], caption['end'], subtext))
        subs.append(file)
    return subs
项目:xbmctopython    作者:pybquillast    | 项目源码 | 文件源码
def getFile(url):
    import xbmc
    # from KodiAddonIDE.KodiStubs.xbmcModules import xbmc
    basePath, queryStr = url.split('/?', 1)
    query = urlparse.parse_qs(queryStr)
    fname, key = query['fname'][0], query['key'][0]
    basePath = xbmc.translatePath(basePath)
    fname = os.path.join(basePath, fname)
    answ = {}
    if key == hashlib.md5(open(fname, 'rb').read()).hexdigest():
        answ['Content-Type'] = 'image/' + os.path.splitext(fname)[1][1:]
        with open(fname, 'rb') as f: answ['body'] = f.read()
    else:
        answ['body'] = '<html><head><title>403 Forbidden</title></head>' \
                       '<body bgcolor="white"><br>' \
                       '<table border="0" align="center" width="720"><tr><td><h1>403 Forbidden</h1>' \
                       '<table style="border: 1px solid #f2f2f2;" bgcolor="#ffffff" align="center" width="720">' \
                       '<tr><td border="0"><tr><td><br><center><h2> server refuses to respond to request </h2>' \
                       '</center><br></td></tr></table><br><center>kodiserver</center></td></tr></table></body></html>'
        answ['Content-Type'] = 'text/html'
    return answ
项目: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
项目:xbmctopython    作者:pybquillast    | 项目源码 | 文件源码
def getSetting(self, stringId):
        """
        --Returns the value of a setting as a unicode string.
        stringId : string - id of the setting that the module needs to access.
        example:
            - apikey = self.Addon.getSetting('apikey')
        """
        home = self.addonPath
        profile = os.path.dirname(os.path.dirname(home)) + '/userdata'
        settingFiles = [('value', profile + '/addon_data/' + self.addonId + '/settings.xml'),
                        ('default', home + '/resources/settings.xml')]

        for attrId, settingXmlFile in settingFiles:
            settingXmlFile = xbmc.translatePath(settingXmlFile)
            if not os.path.exists(settingXmlFile): continue
            root = self._parseXml(settingXmlFile)
            srchStr = './/setting[@id="' + stringId + '"]'
            element = root.find(srchStr)
            if element is not None: return element.get(attrId)
        return ''
项目:xbmctopython    作者:pybquillast    | 项目源码 | 文件源码
def setSetting(self,settingId, value):
        """
        --Sets a script setting.
        addonId : string - id of the setting that the module needs to access. value : string or unicode - value of the setting.
        *Note, You can use the above as keywords for arguments.
        example:
            - self.Settings.setSetting(id='username', value='teamxbmc')
        """
        settingXmlFile = xbmc.translatePath('special://profile/addon_data/' + self.addonId + '/settings.xml')
        tree = ET.parse(settingXmlFile)
        root = tree.getroot()
        srchStr = './/setting[@id="' + settingId + '"]'
        element = root.find(srchStr)
        if element is None:
            element = ET.Element('setting', attrib={'id':settingId, 'value':''})
            root.append(element)
        element.set('value', str(value))
        elemList = sorted(root.getchildren(), key = lambda x: x.get('id'))
        with open(settingXmlFile, 'w') as f:
            f.write('<?xml version="1.0" ?>\n<settings>\n')
            for elem in elemList:
                setStr = '    ' + ET.tostring(elem, 'utf-8').strip() + '\n'
                f.write(setStr)
            f.write('</settings>\n')
        pass
项目:plugin.program.indigo    作者:tvaddonsco    | 项目源码 | 文件源码
def clear_cache():
    kodi.log('STARTUP CLEAR CACHE ACTIVATED')
    xbmc_cache_path = os.path.join(xbmc.translatePath('special://home'), 'cache')
    if os.path.exists(xbmc_cache_path) == True:
        for root, dirs, files in os.walk(xbmc_cache_path):
            file_count = 0
            file_count += len(files)
            if file_count > 0:
                for f in files:
                    try:
                        os.unlink(os.path.join(root, f))
                    except:
                        pass
                for d in dirs:
                    if 'archive_cache' not in d:
                        try:
                            shutil.rmtree(os.path.join(root, d))
                        except:
                            pass
        kodi.log('Startup Service could not clear cache')
项目:plugin.program.indigo    作者:tvaddonsco    | 项目源码 | 文件源码
def art(f, fe=''):
    fe1 = '.png'
    fe2 = '.jpg'
    fe3 = '.gif'
    fe4 = '.wav'
    fe5 = '.txt'
    if fe1 in f:
        f = f.replace(fe1, ''); fe = fe1
    elif fe2 in f:
        f = f.replace(fe2, ''); fe = fe2
    elif fe3 in f:
        f = f.replace(fe3, ''); fe = fe3
    elif fe4 in f:
        f = f.replace(fe4, ''); fe = fe4
    elif fe5 in f:
        f = f.replace(fe5, ''); fe = fe5
    return xbmc.translatePath(os.path.join(artPath, f + fe))
项目:plugin.program.indigo    作者:tvaddonsco    | 项目源码 | 文件源码
def delete_crash_logs(auto_clear=False):
    if not auto_clear:
        if not xbmcgui.Dialog().yesno(AddonName, 'Delete Crash Logs', "Do you want to delete old crash logs?"):
            return
    cache_directories = (xbmc.translatePath('special://home'),
                         os.path.join(xbmc.translatePath('special://home'), 'cache'),
                         xbmc.translatePath('special://temp'))
    for cache_directory in cache_directories:
        if os.path.exists(cache_directory):
            file_types = ('*.dmp', '*.txt')
            import glob
            for file_type in file_types:
                for infile in glob.glob(cache_directory + file_type):
                    os.remove(infile)
    if not auto_clear:
        xbmcgui.Dialog().ok(AddonName, "Crash logs deleted")
项目:plugin.program.indigo    作者:tvaddonsco    | 项目源码 | 文件源码
def auto_weekly_clean_on_off():
    if kodi.get_setting("clearday") == '7':
        if xbmcgui.Dialog().yesno(AddonName, 'Please confirm that you wish to enable weekly automated maintenance.'):
            kodi.set_setting("clearday", datetime.datetime.today().weekday())
            kodi.openSettings(addon_id, id1=5, id2=3)
            available_space, total_space = get_free_space_mb(xbmc.translatePath('special://home'))
            mb_settings = (0, 25, 50, 75, 100)
            while True:
                allotted_space = 0
                for value in ('cachemb', 'thumbsmb', 'packagesmb'):
                    allotted_space += mb_settings[int(kodi.get_setting(value))] * 10 ** 6
                if (allotted_space >= available_space) and not kodi.get_setting("automb"):
                    xbmcgui.Dialog().ok("Your settings sizes for Kodi to use are larger than the available drive space",
                                        'Please try lower settings, uninstall uneeded apps and addons,',
                                        'or set kodi size to "Auto" to use the automated settings based on free space')
                    kodi.openSettings(addon_id, id1=5, id2=3)
                else:
                    break
    else:
        if xbmcgui.Dialog().yesno(AddonName, 'Please confirm that you wish to disable weekly automated maintenance.'):
            kodi.set_setting("clearday", '7')
    xbmc.executebuiltin("Container.Refresh")
项目:plugin.video.psvue    作者:eracknaphobia    | 项目源码 | 文件源码
def check_login(self):
        expired_cookies = True
        addon_profile_path = xbmc.translatePath(self.addon.getAddonInfo('profile'))
        try:
            cj = cookielib.LWPCookieJar()
            cj.load(os.path.join(addon_profile_path, 'cookies.lwp'), ignore_discard=True)
            if self.npsso != '':
                for cookie in cj:
                    if cookie.name == 'npsso':
                        expired_cookies = cookie.is_expired()
                        break
        except:
            pass

        if expired_cookies:
            self.login()
项目: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 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()]))
项目:addon    作者:alfa-addon    | 项目源码 | 文件源码
def __init__(self, url, mode="r"):
        import random
        try:
            import xbmc
        except:
            xbmc = None
        self.url = url
        self.remote, self.share, self.path = path = connect(url)
        self.mode = mode
        self.binary = False
        self.canread = False
        self.canwrite = False
        self.closed = True
        self.size = 0
        self.pos = 0
        if xbmc:
            self.tmp_path = os.path.join(xbmc.translatePath("special://temp/"), "%08x" % (random.getrandbits(32)))
        else:
            self.tmp_path = os.path.join(os.getenv("TEMP") or os.getenv("TMP") or os.getenv("TMPDIR"),
                                         "%08x" % (random.getrandbits(32)))
        self.tmp_file = None

        self.__get_mode__()
项目:YoutubeTV    作者:dude56987    | 项目源码 | 文件源码
def loadFile(fileName):
    '''
    Load a file with the path fileName.

    Returns the loaded file as a string or if the
    file fails to load return False.

    :return bool/string
    '''
    # this is where all files related to the plugin will be stored
    basePath=('special://userdata/addon_data/'+_id+'/')
    basePath=xbmc.translatePath(basePath)
    # concat the basepath and file fileName for the file to load
    path=(basePath+fileName)
    # check if the config file exists already
    if os.path.exists(path):
        # open the file to write
        fileObject=open(path,'r')
        # temp string to hold file content
        temp=''
        # read each line into a string
        for line in fileObject:
            temp+=line
        # return the contents of the file as a string
        return temp
        # return the string text of the file
        #return fileObject.read()
    else:
        # return false if the file is not found
        return False
项目:cmik.xbmc    作者:cmik    | 项目源码 | 文件源码
def checkAccountChange(forceSignIn=False):
    email = setting('emailAddress')
    password = setting('password')
    hash = hashlib.sha1(email + password).hexdigest()
    hashFile = os.path.join(xbmc.translatePath(addonInfo('profile')), 'a.tmp')
    savedHash = ''
    accountChanged = False
    logged = False
    loginSuccess = False

    if os.path.exists(hashFile):
        if forceSignIn == True: 
            os.unlink(hashFile)
        else: 
            with open(hashFile) as f:
                savedHash = f.read()

    if savedHash != hash:
        accountChanged = True
        logout()
        logged = True
    elif not isLoggedIn():
        log('Not logged in')
        logged = True

    if logged:
        loginSuccess = login()
        if loginSuccess == True and os.path.exists(xbmc.translatePath(addonInfo('profile'))):
            with open(hashFile, 'w') as f:
                f.write(hash)
        elif os.path.exists(hashFile)==True: 
            os.unlink(hashFile)

    return (accountChanged, loginSuccess)
项目:cmik.xbmc    作者:cmik    | 项目源码 | 文件源码
def cleanCookies(notify=True):
    message = ''
    if os.path.exists(os.path.join(xbmc.translatePath('special://home'), 'cache', 'cookies.dat'))==True:  
        log('cookies file FOUND (cache)')
        try: 
            os.unlink(os.path.join(xbmc.translatePath('special://home'), 'cache', 'cookies.dat'))
            message = lang(57004)
        except: 
            message = lang(57005)

    elif os.path.exists(os.path.join(xbmc.translatePath('special://home'), 'temp', 'cookies.dat'))==True:  
        log('cookies file FOUND (temp)')
        try: 
            os.unlink(os.path.join(xbmc.translatePath('special://home'), 'temp', 'cookies.dat'))
            message = lang(57004)
        except: 
            message = lang(57005)
    elif os.path.exists(os.path.join(xbmc.translatePath(addonInfo('profile')), cookieFileName))==True:  
        log('cookies file FOUND (profile)')
        try: 
            os.unlink(os.path.join(xbmc.translatePath(addonInfo('profile')), cookieFileName))
            message = lang(57004)
        except: 
            message = lang(57005)
    else:
        message = lang(57006)

    if notify == True:
        showNotification(message)

#---------------------- MAIN ----------------------------------------
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def backup(self, filters=None, backup_file="", silent=False):
        '''create skin backup'''
        if not filters:
            filters = []

        if not backup_file:
            return

        # create temp path
        temp_path = self.create_temp()
        zip_temp = u'%s/skinbackup-%s.zip' % (temp_path, datetime.now().strftime('%Y-%m-%d %H.%M'))
        temp_path = temp_path + "skinbackup/"

        # backup skinshortcuts preferences
        if not filters or (filters and "skinshortcuts" in filters):
            self.backup_skinshortcuts(temp_path + "skinshortcuts/")

        # backup skin settings
        if "skinshortcutsonly" not in filters:
            skinsettings_path = os.path.join(temp_path, u"guisettings.txt")
            self.backup_skinsettings(skinsettings_path, filters, temp_path)

        # zip the backup
        zip_temp = xbmc.translatePath(zip_temp).decode("utf-8")
        zip_tofile(temp_path, zip_temp)

        # copy file to destination - wait untill it's really copied
        copy_file(zip_temp, backup_file, True)

        # cleanup temp
        recursive_delete_dir(temp_path)
        xbmcvfs.delete(zip_temp)

        # show success message
        if not silent:
            xbmcgui.Dialog().ok(self.addon.getLocalizedString(32004), self.addon.getLocalizedString(32005))
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def backup_skinshortcuts_images(shortcutfile, dest_path):
        '''parse skinshortcuts file and copy images to backup location'''
        shortcutfile = xbmc.translatePath(shortcutfile).decode("utf-8")
        doc = parse(shortcutfile)
        listing = doc.documentElement.getElementsByTagName('shortcut')
        for shortcut in listing:
            defaultid = shortcut.getElementsByTagName('defaultID')
            if defaultid:
                defaultid = defaultid[0].firstChild
                if defaultid:
                    defaultid = defaultid.data
                if not defaultid:
                    defaultid = shortcut.getElementsByTagName('label')[0].firstChild.data
                thumb = shortcut.getElementsByTagName('thumb')
                if thumb:
                    thumb = thumb[0].firstChild
                    if thumb:
                        thumb = thumb.data
                        if thumb and (thumb.endswith(".jpg") or thumb.endswith(".png") or thumb.endswith(".gif")):
                            thumb = get_clean_image(thumb)
                            extension = thumb.split(".")[-1]
                            newthumb = os.path.join(dest_path, "%s-thumb-%s.%s" %
                                                    (xbmc.getSkinDir(), normalize_string(defaultid), extension))
                            newthumb_vfs = "special://profile/addon_data/script.skinshortcuts/%s-thumb-%s.%s" % (
                                xbmc.getSkinDir(), normalize_string(defaultid), extension)
                            if xbmcvfs.exists(thumb):
                                copy_file(thumb, newthumb)
                                shortcut.getElementsByTagName('thumb')[0].firstChild.data = newthumb_vfs
        # write changes to skinshortcuts file
        shortcuts_file = xbmcvfs.File(shortcutfile, "w")
        shortcuts_file.write(doc.toxml(encoding='utf-8'))
        shortcuts_file.close()
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def get_skinsettings(filters=None):
        '''get all active skin settings'''
        all_skinsettings = []
        guisettings_path = 'special://profile/addon_data/%s/settings.xml' % xbmc.getSkinDir()
        if xbmcvfs.exists(guisettings_path):
            doc = parse(xbmc.translatePath(guisettings_path).decode("utf-8"))
            skinsettings = doc.documentElement.getElementsByTagName('setting')
            for skinsetting in skinsettings:
                settingname = skinsetting.attributes['id'].nodeValue
                settingtype = skinsetting.attributes['type'].nodeValue
                if isinstance(settingname, unicode):
                    settingname = settingname.encode("utf-8")
                # we must grab the actual values because the xml file only updates at restarts
                if settingtype == "bool":
                    if "$INFO" not in settingname and xbmc.getCondVisibility("Skin.HasSetting(%s)" % settingname):
                        settingvalue = "true"
                    else:
                        settingvalue = "false"
                else:
                    settingvalue = xbmc.getInfoLabel("Skin.String(%s)" % settingname)
                if not filters:
                    # no filter - just add all settings we can find
                    all_skinsettings.append((settingtype, settingname, settingvalue))
                else:
                    # only select settings defined in our filters
                    for filteritem in filters:
                        if filteritem.lower() in settingname.lower():
                            all_skinsettings.append((settingtype, settingname, settingvalue))
        return all_skinsettings
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def unzip_fromfile(zip_path, dest_path):
    '''method to unzip a zipfile to a destination path'''
    import shutil
    import zipfile
    zip_path = xbmc.translatePath(zip_path).decode("utf-8")
    dest_path = xbmc.translatePath(dest_path).decode("utf-8")
    log_msg("START UNZIP of file %s  to path %s " % (zip_path, dest_path))
    zip_file = zipfile.ZipFile(zip_path, 'r')
    for fileinfo in zip_file.infolist():
        filename = fileinfo.filename
        if not isinstance(filename, unicode):
            filename = filename.decode("utf-8")
        log_msg("unzipping: " + filename)
        splitter = None
        if "\\" in filename:
            xbmcvfs.mkdirs(os.path.join(dest_path, filename.rsplit("\\", 1)[0]))
            splitter = "\\"
        elif "/" in filename:
            xbmcvfs.mkdirs(os.path.join(dest_path, filename.rsplit("/", 1)[0]))
            splitter = "/"
        filename = os.path.join(dest_path, filename)
        if not (splitter and filename.endswith(splitter)):
            try:
                # newer python uses unicode
                outputfile = open(filename, "wb")
            except Exception:
                # older python uses utf-8
                outputfile = open(filename.encode("utf-8"), "wb")
            # use shutil to support non-ascii formatted files in the zip
            shutil.copyfileobj(zip_file.open(fileinfo.filename), outputfile)
            outputfile.close()
    zip_file.close()
    log_msg("UNZIP DONE of file %s  to path %s " % (zip_path, dest_path))
项目:plugin.video.bdyun    作者:caasiu    | 项目源码 | 文件源码
def data_dir():
    """"get user data directory of this addon. 
    according to http://wiki.xbmc.org/index.php?title=Add-on_Rules#Requirements_for_scripts_and_plugins
    """
    __datapath__ = xbmc.translatePath( __Addon.getAddonInfo('profile') ).decode('utf-8')
    if not xbmcvfs.exists(__datapath__):
        xbmcvfs.mkdir(__datapath__)
    return __datapath__
项目:konsodi    作者:kharts    | 项目源码 | 文件源码
def image(filename):
    """
    Construct full filename of the image, using short name
    and path to addon folder
    :param filename: short filename of the image
    :return: full filename of the image
    :rtype: str
    """

    addon_folder = xbmc.translatePath(this_addon.getAddonInfo("path"))
    return os.path.join(addon_folder,
                        "resources",
                        "img",
                        filename)
项目: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.telekom-sport    作者:asciidisco    | 项目源码 | 文件源码
def get_addon_data(self):
        """
        Returns the relevant addon data for the plugin,
        e.g. name, version, default fanart, base data path & cookie pathname

        :returns:  dict - Addon data
        """
        addon = self.get_addon()
        base_data_path = xbmc.translatePath(addon.getAddonInfo('profile'))
        return dict(
            plugin=addon.getAddonInfo('name'),
            version=addon.getAddonInfo('version'),
            fanart=addon.getAddonInfo('fanart'),
            base_data_path=base_data_path,
            cookie_path=base_data_path + 'COOKIE')