Python xbmcvfs.mkdirs() Examples

The following are 30 code examples of xbmcvfs.mkdirs(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xbmcvfs , or try the search function .
Example #1
Source File: utils.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def copytree(path, dest):

    ''' Copy folder content from one to another.
    '''
    dirs, files = xbmcvfs.listdir(path)

    if not xbmcvfs.exists(dest):
        xbmcvfs.mkdirs(dest)

    if dirs:
        copy_recursive(path, dirs, dest)

    for file in files:
        copy_file(os.path.join(path, file.decode('utf-8')), os.path.join(dest, file.decode('utf-8')))

    LOG.info("Copied %s", path) 
Example #2
Source File: __init__.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def get_sync():

    path = xbmc.translatePath("special://profile/addon_data/plugin.video.emby/").decode('utf-8')
    
    if not xbmcvfs.exists(path):
        xbmcvfs.mkdirs(path)

    try:
        with open(os.path.join(path, 'sync.json')) as infile:
            sync = json.load(infile)
    except Exception:
        sync = {}

    sync['Libraries'] = sync.get('Libraries', [])
    sync['RestorePoint'] = sync.get('RestorePoint', {})
    sync['Whitelist'] = list(set(sync.get('Whitelist', [])))
    sync['SortedViews'] = sync.get('SortedViews', [])

    return sync 
Example #3
Source File: speedtest.py    From plugin.program.indigo with GNU General Public License v3.0 6 votes vote down vote up
def make_dir(mypath, dirname):
    ''' Creates sub-directories if they are not found. '''
    import xbmcvfs

    if not xbmcvfs.exists(mypath):
        try:
            xbmcvfs.mkdirs(mypath)
        except:
            xbmcvfs.mkdir(mypath)

    subpath = os.path.join(mypath, dirname)

    if not xbmcvfs.exists(subpath):
        try:
            xbmcvfs.mkdirs(subpath)
        except:
            xbmcvfs.mkdir(subpath)

    return subpath


# ----------------------------------------------------------------------------------------------------------------- 
Example #4
Source File: __init__.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def get_credentials():

    path = xbmc.translatePath("special://profile/addon_data/plugin.video.emby/").decode('utf-8')
    
    if not xbmcvfs.exists(path):
        xbmcvfs.mkdirs(path)

    try:
        with open(os.path.join(path, 'data.json')) as infile:
            credentials = json.load(infile)
    except Exception:

        try:
            with open(os.path.join(path, 'data.txt')) as infile:
                credentials = json.load(infile)
                save_credentials(credentials)
            
            xbmcvfs.delete(os.path.join(path, 'data.txt'))
        except Exception:
            credentials = {}

    credentials['Servers'] = credentials.get('Servers', [])

    return credentials 
Example #5
Source File: vfs.py    From plugin.git.browser with GNU General Public License v3.0 6 votes vote down vote up
def mkdir(path, recursive=False):
	if exists(path):
		if debug:
			xbmc.log('******** VFS mkdir notice: %s exists' % path)
		return False
	if recursive:
		try:
			return xbmcvfs.mkdirs(path)
		except Exception as e:
			xbmc.log('******** VFS error: %s' % e)
			return False
	else:
		try:
			return xbmcvfs.mkdir(path)
		except Exception as e:
			xbmc.log('******** VFS error: %s' % e)
			return False 
Example #6
Source File: sutils.py    From plugin.video.sosac.ph with GNU General Public License v2.0 6 votes vote down vote up
def add_item_to_library(self, item_path, item_url):
        error = False
        new = False
        if item_path:
            item_path = xbmc.translatePath(item_path)
            dir = os.path.dirname(item_path)
            if not xbmcvfs.exists(dir):
                try:
                    xbmcvfs.mkdirs(dir)
                except Exception, e:
                    error = True
                    util.error('Failed to create directory 1: ' + dir)

            if not xbmcvfs.exists(item_path):
                try:
                    file_desc = xbmcvfs.File(item_path, 'w')
                    file_desc.write(item_url)
                    file_desc.close()
                    new = True
                except Exception, e:
                    util.error('Failed to create .strm file: ' +
                               item_path + " | " + str(e))
                    error = True 
Example #7
Source File: service.py    From service.subtitles.addic7ed with GNU General Public License v2.0 6 votes vote down vote up
def download(link):
  subtitle_list = []

  if xbmcvfs.exists(__temp__):
    shutil.rmtree(__temp__)
  xbmcvfs.mkdirs(__temp__)

  file = os.path.join(__temp__, "addic7ed.srt")

  f = get_url(link)

  local_file_handle = open(file, "wb")
  local_file_handle.write(f)
  local_file_handle.close()

  subtitle_list.append(file)

  if len(subtitle_list) == 0:
    if search_string:
      xbmc.executebuiltin((u'Notification(%s,%s)' % (__scriptname__ , __language__(32002))).encode('utf-8'))
    else:
      xbmc.executebuiltin((u'Notification(%s,%s)' % (__scriptname__ , __language__(32003))).encode('utf-8'))

  return subtitle_list 
Example #8
Source File: playerMP3.py    From bugatsinho.github.io with GNU General Public License v3.0 6 votes vote down vote up
def createFilename(title, artist, album, url):
    if ADDON.getSetting('keep_downloads')=='false':
        return os.path.join(TEMP, createMD5(url))

    title  = clean(title)
    artist = clean(artist)
    album  = clean(album)

    customdir = ADDON.getSetting('custom_directory')
    folder = ADDON.getSetting('music_dir')

    if customdir=='false':
        folder = TEMP

    if ADDON.getSetting('folder_structure')=="0":
        filename = os.path.join(folder, artist, album)
    else:
        filename = os.path.join(folder, artist + ' - ' + album)
 
    try:
        xbmcvfs.mkdirs(filename)
    except Exception, e:
        log('Error creating folder %s - %s' % (filename, str(e))) 
Example #9
Source File: context.py    From plugin.video.themoviedb.helper with GNU General Public License v3.0 5 votes vote down vote up
def library_createpath(path):
    if xbmcvfs.exists(path):
        return path
    if xbmcvfs.mkdirs(path):
        utils.kodi_log(u'ADD LIBRARY -- Created path:\n{}'.format(path), 2)
        return path
    if _addon.getSettingBool('ignore_folderchecking'):
        utils.kodi_log(u'ADD LIBRARY -- xbmcvfs reports folder does NOT exist:\n{}\nIGNORING ERROR: User set folder checking to ignore'.format(path), 2)
        return path 
Example #10
Source File: utils.py    From plugin.video.themoviedb.helper with GNU General Public License v3.0 5 votes vote down vote up
def makepath(path):
    if xbmcvfs.exists(path):
        return xbmc.translatePath(path)
    xbmcvfs.mkdirs(path)
    return xbmc.translatePath(path) 
Example #11
Source File: filemanager.py    From script.artwork.beef with MIT License 5 votes vote down vote up
def recyclefile(filename):
    firstdir = utils.parent_dir(filename)
    directory = TEMP_DIR
    pathsep = utils.get_pathsep(directory)
    if firstdir in ('extrafanart', 'extrathumbs'):
        directory += utils.parent_dir(os.path.dirname(filename)) + pathsep
    directory += firstdir
    if not xbmcvfs.exists(directory):
        xbmcvfs.mkdirs(directory)
    recycled_filename = directory + pathsep + os.path.basename(filename)
    if not xbmcvfs.copy(filename, recycled_filename):
        raise FileError(L(CANT_WRITE_TO_FILE).format(recycled_filename)) 
Example #12
Source File: mediainfo.py    From script.artwork.beef with MIT License 5 votes vote down vote up
def _get_sourcemedia(mediapath):
    if not mediapath:
        return 'unknown'
    mediapath = mediapath.lower()
    if re.search(r'\b3d\b', mediapath):
        return '3d'
    # TODO: UHD?
    if re.search(r'blu-?ray|b[rd]-?rip', mediapath) or mediapath.endswith('.bdmv'):
        return 'bluray'
    if re.search(r'\bdvd', mediapath) or mediapath.endswith('.ifo'):
        return 'dvd'
    return 'unknown'

# REVIEW: there may be other protocols that just can't be written to
#  xbmcvfs.mkdirs only supports local drives, SMB, and NFS 
Example #13
Source File: filetools.py    From addon with GNU General Public License v3.0 5 votes vote down vote up
def mkdir(path, silent=False, vfs=True):
    """
    Crea un directorio
    @param path: ruta a crear
    @type path: str
    @rtype: bool
    @return: devuelve False en caso de error
    """
    path = encode(path)
    try:
        if xbmc_vfs and vfs:
            if not path.endswith('/') and not path.endswith('\\'):
                path = join(path, ' ').rstrip()
            result = bool(xbmcvfs.mkdirs(path))
            if not result:
                import time
                time.sleep(0.1)
                result = exists(path)
            return result
        elif path.lower().startswith("smb://"):
            samba.mkdir(path)
        else:
            os.mkdir(path)
    except:
        logger.error("ERROR al crear el directorio: %s" % path)
        if not silent:
            logger.error(traceback.format_exc())
            platformtools.dialog_notification("Error al crear el directorio", path)
        return False
    else:
        return True 
Example #14
Source File: default.py    From xbmc-addons-chinese with GNU General Public License v2.0 5 votes vote down vote up
def playlist_path(pcs_file_path, stream):
    user_info = get_user_info()
    user_name = user_info['username']
    user_cookie = user_info['cookie']
    user_tokens = user_info['tokens']

    if stream:
        playlist_data = pcs.get_streaming_playlist(user_cookie, pcs_file_path, stream)
        if playlist_data:
            raw_dir = os.path.dirname(pcs_file_path)
            m = re.search('\/(.*)', raw_dir)
            dirname = m.group(1)
            basename = os.path.basename(pcs_file_path)
            r = re.search('(.*)\.(.*)$', basename)
            filename = ''.join([r.group(1), stream, '.m3u8'])
            dirpath = os.path.join(utils.data_dir(), user_name, dirname)
            if not xbmcvfs.exists(dirpath):
                xbmcvfs.mkdirs(dirpath)
            filepath = os.path.join(dirpath, filename)
            tmpFile = xbmcvfs.File(filepath, 'w')
            tmpFile.write(bytearray(playlist_data, 'utf-8'))
            return filepath
        else:
            dialog.notification('', u'无法打开视频', xbmcgui.NOTIFICATION_INFO, 4000)
            return None
    else:
        url = pcs.stream_download(user_cookie, user_tokens, pcs_file_path)
        if url:
            return url
        else:
            dialog.notification('', u'无法打开原画,请尝试流畅模式', xbmcgui.NOTIFICATION_INFO, 4000)
            return None 
Example #15
Source File: main.py    From plugin.video.iptv.recorder with GNU General Public License v3.0 5 votes vote down vote up
def delete_job(job, kill=True, ask=True):
    conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')), detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
    cursor = conn.cursor()

    job_details = cursor.execute("SELECT uuid FROM jobs WHERE uuid=?", (job, )).fetchone()
    if not job_details:
        return

    if ask and not (xbmcgui.Dialog().yesno("IPTV Recorder", _("Cancel Record?"))):
        return

    if windows() and plugin.get_setting('task.scheduler') == 'true':
        cmd = ["schtasks", "/delete", "/f", "/tn", job]
        subprocess.Popen(cmd, shell=True)
    else:
        xbmc.executebuiltin('CancelAlarm(%s, True)' % job)

    directory = "special://profile/addon_data/plugin.video.iptv.recorder/jobs/"
    xbmcvfs.mkdirs(directory)
    pyjob = directory + job + ".py"

    pid = xbmcvfs.File(pyjob+'.pid').read()

    xbmcvfs.delete(pyjob)
    xbmcvfs.delete(pyjob+'.pid')

    if pid and kill:
        if windows():
            subprocess.Popen(["taskkill", "/im", pid], shell=True)
        else:
            #TODO correct kill switch
            subprocess.Popen(["kill", "-9", pid])

    conn.execute("DELETE FROM jobs WHERE uuid=?", (job, ))
    conn.commit()
    conn.close()

    refresh() 
Example #16
Source File: utils.py    From script.module.clouddrive.common with GNU General Public License v3.0 5 votes vote down vote up
def mkdirs(f):
        import xbmcvfs
        return xbmcvfs.mkdirs(f) 
Example #17
Source File: default.py    From plugin.video.bdyun with GNU General Public License v3.0 5 votes vote down vote up
def playlist_path(pcs_file_path, stream):
    user_info = get_user_info()
    user_name = user_info['username']
    user_cookie = user_info['cookie']
    user_tokens = user_info['tokens']

    if stream:
        playlist_data = pcs.get_streaming_playlist(user_cookie, pcs_file_path, stream)
        if playlist_data:
            raw_dir = os.path.dirname(pcs_file_path)
            m = re.search('\/(.*)', raw_dir)
            dirname = m.group(1)
            basename = os.path.basename(pcs_file_path)
            r = re.search('(.*)\.(.*)$', basename)
            filename = ''.join([r.group(1), stream, '.m3u8'])
            dirpath = os.path.join(utils.data_dir(), user_name, dirname)
            if not xbmcvfs.exists(dirpath):
                xbmcvfs.mkdirs(dirpath)
            filepath = os.path.join(dirpath, filename)
            tmpFile = xbmcvfs.File(filepath, 'w')
            tmpFile.write(bytearray(playlist_data, 'utf-8'))
            return filepath
        else:
            dialog.notification('', u'无法打开视频', xbmcgui.NOTIFICATION_INFO, 4000)
            return None
    else:
        url = pcs.stream_download(user_cookie, user_tokens, pcs_file_path)
        if url:
            return url
        else:
            dialog.notification('', u'无法打开原画,请尝试流畅模式', xbmcgui.NOTIFICATION_INFO, 4000)
            return None 
Example #18
Source File: kodiutils.py    From plugin.video.vrt.nu with GNU General Public License v3.0 5 votes vote down vote up
def mkdirs(path):
    """Create directory including parents (using xbmcvfs)"""
    from xbmcvfs import mkdirs as vfsmkdirs
    log(3, "Recursively create directory '{path}'.", path=path)
    return vfsmkdirs(path) 
Example #19
Source File: tools.py    From plugin.program.openwizard with GNU General Public License v3.0 5 votes vote down vote up
def ensure_folders(folder=None):
    import xbmcvfs

    name = ''
    folders = [CONFIG.BACKUPLOCATION, CONFIG.MYBUILDS, CONFIG.PLUGIN_DATA,
               CONFIG.USERDATA, CONFIG.ADDON_DATA, CONFIG.PACKAGES]

    try:
        if folder is not None and not os.path.exists(folder):
            name = folder
            xbmcvfs.mkdirs(folder)
            return

        for f in folders:
            if not os.path.exists(f):
                name = f
                xbmcvfs.mkdirs(f)

    except Exception as e:
        dialog = xbmcgui.Dialog()

        dialog.ok(CONFIG.ADDONTITLE,
                      "[COLOR {0}]Error creating add-on directories:[/COLOR]".format(CONFIG.COLOR2),
                      "[COLOR {0}]{1}[/COLOR]".format(CONFIG.COLOR1, name))

#########################
#  Utility Functions    #
######################### 
Example #20
Source File: views.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def verify_kodi_defaults():

    ''' Make sure we have the kodi default folder in place.
    '''
    node_path = xbmc.translatePath("special://profile/library/video").decode('utf-8')

    if not xbmcvfs.exists(node_path):
        try:
            shutil.copytree(
                src=xbmc.translatePath("special://xbmc/system/library/video").decode('utf-8'),
                dst=xbmc.translatePath("special://profile/library/video").decode('utf-8'))
        except Exception as error:
            xbmcvfs.mkdir(node_path)

    for index, node in enumerate(['movies', 'tvshows', 'musicvideos']):
        file = os.path.join(node_path, node, "index.xml")

        if xbmcvfs.exists(file):

            try:
                xml = etree.parse(file).getroot()
            except Exception as error:
                LOG.error(error) 

                continue

            xml.set('order', str(17 + index))
            indent(xml)
            write_xml(etree.tostring(xml, 'UTF-8'), file)

    playlist_path = xbmc.translatePath("special://profile/playlists/video").decode('utf-8')

    if not xbmcvfs.exists(playlist_path):
        xbmcvfs.mkdirs(playlist_path) 
Example #21
Source File: __init__.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def save_sync(sync):

    path = xbmc.translatePath("special://profile/addon_data/plugin.video.emby/").decode('utf-8')
    
    if not xbmcvfs.exists(path):
        xbmcvfs.mkdirs(path)

    sync['Date'] = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')

    with open(os.path.join(path, 'sync.json'), 'w') as outfile:
        json.dump(sync, outfile, sort_keys=True, indent=4, ensure_ascii=False) 
Example #22
Source File: xbmclibrary.py    From plugin.video.ustvvod with GNU General Public License v2.0 5 votes vote down vote up
def CreateDirectory(self, dir_path):
		os.path.join(dir_path, '') # ensure the path terminates in a '/'
		if not xbmcvfs.exists(dir_path):
			xbmcvfs.mkdirs(dir_path) 
Example #23
Source File: utils.py    From script.tvguide.fullscreen with GNU General Public License v2.0 5 votes vote down vote up
def getLogo(title,ask=False,force=True):
    infile = xbmc.translatePath("special://profile/addon_data/script.tvguide.fullscreen/logos/temp.png")
    outfile = xbmc.translatePath("special://profile/addon_data/script.tvguide.fullscreen/logos/%s.png" % title)
    if not force and xbmcvfs.exists(outfile):
        return outfile
    xbmcvfs.mkdirs("special://profile/addon_data/script.tvguide.fullscreen/logos")
    db_url = "http://www.thelogodb.com/api/json/v1/4423/tvchannel.php?s=%s" % re.sub(' ','+',title)
    try: json = requests.get(db_url).json()
    except: return None
    if json and "channels" in json:
        channels = json["channels"]
        if channels:
            if ask:
                names = ["%s [%s]" % (c["strChannel"],c["strCountry"]) for c in channels]
                d = xbmcgui.Dialog()
                selected = d.select("Logo Source: %s" % title,names)
            else:
                selected = 0
            if selected > -1:
                logo = channels[selected]["strLogoWide"]

                if not logo:
                    return None
                logo = re.sub('^https','http',logo)
                data = requests.get(logo).content
                f = xbmcvfs.File("special://profile/addon_data/script.tvguide.fullscreen/logos/temp.png","wb")
                f.write(data)
                f.close()
                from PIL import Image, ImageOps
                image = Image.open(infile)
                border = 0
                image = autocrop_image(image, border)
                image.save(outfile)
                logo = outfile
                return logo 
Example #24
Source File: channel_logos.py    From script.tvguide.fullscreen with GNU General Public License v2.0 5 votes vote down vote up
def onInitialized(success):
        if success:
            channelList = database.getChannelList(onlyVisible=False)
            xbmcvfs.mkdirs("special://profile/addon_data/script.tvguide.fullscreen/channel_logos/")
            for channel in channelList:
                from_file = channel.logo
                regex = '[%s]' % re.escape('[]/\:')
                xbmc.log(regex)
                ext = from_file.rsplit('.',1)[-1]
                to_file = "special://profile/addon_data/script.tvguide.fullscreen/channel_logos/%s.%s" % (re.sub(regex,' ',channel.title),ext)
                xbmcvfs.copy(from_file,to_file)
            database.close(onAutoplaysCleared)
        else:
            database.close() 
Example #25
Source File: playerMP3.py    From bugatsinho.github.io with GNU General Public License v3.0 5 votes vote down vote up
def resetCache():
    log('in RESETCACHE')
    if not xbmcvfs.exists(TEMP):
        try:    xbmcvfs.mkdirs(TEMP)
        except: pass
        return

    dirs, files = xbmcvfs.listdir(TEMP)
    for file in files:
        filename = os.path.join(TEMP, file)
        deleteFile(filename) 
Example #26
Source File: db_utils.py    From plugin.video.netflix with MIT License 5 votes vote down vote up
def get_local_db_path(db_filename):
    # First ensure database folder exists
    db_folder = g.py2_decode(xbmc.translatePath(os.path.join(g.DATA_PATH, 'database')))
    if not folder_exists(db_folder):
        xbmcvfs.mkdirs(db_folder)
    return os.path.join(db_folder, db_filename) 
Example #27
Source File: library_items.py    From plugin.video.netflix with MIT License 5 votes vote down vote up
def _create_destination_folder(destination_folder):
    """Create destination folder, ignore error if it already exists"""
    if not common.folder_exists(destination_folder):
        xbmcvfs.mkdirs(destination_folder) 
Example #28
Source File: kodiutils.py    From script.module.inputstreamhelper with MIT License 5 votes vote down vote up
def mkdirs(path):
    """Create directory including parents (using xbmcvfs)"""
    from xbmcvfs import mkdirs as vfsmkdirs
    log(2, "Recursively create directory '{path}'.", path=path)
    return vfsmkdirs(from_unicode(path)) 
Example #29
Source File: service.py    From xbmc-addons-chinese with GNU General Public License v2.0 4 votes vote down vote up
def Download(url):
    if not xbmcvfs.exists(__temp__.replace('\\','/')):
        xbmcvfs.mkdirs(__temp__)
    dirs, files = xbmcvfs.listdir(__temp__)
    for file in files:
        xbmcvfs.delete(os.path.join(__temp__, file.decode("utf-8")))

    subtitle_list = []
    exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass" ]
    try:
        data = GetHttpData(url)
        soup = BeautifulSoup(data, 'html.parser')
        url = soup.find("div", class_="subtitle-links").a.get('href').encode('utf-8')
        url = url.replace('subtitle.html', 'api/v1/static/subtitle/detail')
        data = json.loads(GetHttpData(url))
        if data['info'] != 'OK':
            return []
        url = data['data']['info']['file']
        data = GetHttpData(url)
    except:
        return []
    if len(data) < 1024:
        return []
    t = time.time()
    ts = time.strftime("%Y%m%d%H%M%S",time.localtime(t)) + str(int((t - int(t)) * 1000))
    tmpfile = os.path.join(__temp__, "subtitles%s%s" % (ts, os.path.splitext(url)[1])).replace('\\','/')
    with open(tmpfile, "wb") as subFile:
        subFile.write(data)

    xbmc.sleep(500)
    archive = urllib.quote_plus(tmpfile)
    if data[:4] == 'Rar!':
        path = 'rar://%s' % (archive)
    else:
        path = 'zip://%s' % (archive)
    dirs, files = xbmcvfs.listdir(path)
    if ('__MACOSX') in dirs:
        dirs.remove('__MACOSX')
    if len(dirs) > 0:
        path = path + '/' + dirs[0].decode('utf-8')
        dirs, files = xbmcvfs.listdir(path)
    list = []
    for subfile in files:
        if (os.path.splitext( subfile )[1] in exts):
            list.append(subfile.decode('utf-8'))
    if len(list) == 1:
        subtitle_list.append(path + '/' + list[0])
    elif len(list) > 1:
        sel = xbmcgui.Dialog().select('请选择压缩包中的字幕', list)
        if sel == -1:
            sel = 0
        subtitle_list.append(path + '/' + list[sel])

    return subtitle_list 
Example #30
Source File: service.py    From xbmc-addons-chinese with GNU General Public License v2.0 4 votes vote down vote up
def Download(url,lang):
    if not xbmcvfs.exists(__temp__.replace('\\','/')):
        xbmcvfs.mkdirs(__temp__)
    dirs, files = xbmcvfs.listdir(__temp__)
    for file in files:
        xbmcvfs.delete(os.path.join(__temp__, file))

    subtitle_list = []
    exts =(".srt", ".sub", ".txt", ".smi", ".ssa", ".ass")
    try:
        html = session_get(url).text
    except:
        log(sys._getframe().f_code.co_name, "%s (%d) [%s]" % (
               sys.exc_info()[2].tb_frame.f_code.co_name,
               sys.exc_info()[2].tb_lineno,
               sys.exc_info()[1]
               ))
        return []

    soup = BeautifulSoup(html, "html.parser")
    # 预览接口无验证码,可以提取单个字幕文件
    data = soup.find_all('a', text='预览')
    data = [i.get('data-fname').encode('utf-8') for i in data]
    subs = [i for i in data if i.endswith(exts)]

    dialog = xbmcgui.Dialog()
    # 文件名超长时会滚动显示,截断只显示最后50个字符,提高选择效率
    ret = dialog.select("选择字幕", [i[-50:] for i in subs])

    subid = int(url.rsplit('/')[-1])
    fname = urllib.quote(subs[ret])

    data = 'dasid=%d&dafname=%s' % (subid, fname)
    data = session_get('%s/ajax/file_ajax' % SUBHD_BASE, data=data, referer=url).json()
    data = data['filedata'].encode('utf-8').replace('<br />', '')

    if len(data) < 1024:
        return []
    t = time.time()
    ts = time.strftime("%Y%m%d%H%M%S",time.localtime(t)) + str(int((t - int(t)) * 1000))
    tempfile = os.path.join(__temp__, "subtitles%s%s" % (ts, fname[-4:])).replace('\\','/')
    with open(tempfile, "wb") as subFile:
        subFile.write(data)
    subtitle_list.append(tempfile)
    if len(subtitle_list) > 0:
        log(sys._getframe().f_code.co_name, "Get subtitle file: %s" % (subtitle_list[0]))
    return subtitle_list