Python xbmcvfs.listdir() Examples

The following are 30 code examples of xbmcvfs.listdir(). 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: main.py    From plugin.video.iptv.recorder with GNU General Public License v3.0 6 votes vote down vote up
def find(path):
    path = xbmc.translatePath(path)
    all_dirs = []
    all_files = []
    dirs, files = xbmcvfs.listdir(path)
    for file in files:
        file_path = os.path.join(path,file)
        all_files.append(file_path)
    for dir in dirs:
        dir_path = os.path.join(path,dir)
        all_dirs.append(dir_path)
        new_dirs, new_files = find(os.path.join(path, dir))
        for new_dir in new_dirs:
            new_dir_path = os.path.join(path,dir,new_dir)
            all_dirs.append(new_dir_path)
        for new_file in new_files:
            new_file = os.path.join(path,dir,new_file)
            all_files.append(new_file)
    return all_dirs, all_files 
Example #2
Source File: resourceaddons.py    From script.skin.helper.service with GNU General Public License v2.0 6 votes vote down vote up
def walk_directory(browsedir, recursive=False, label2=""):
    '''list all images in a directory'''
    images = []
    if xbmcvfs.exists(browsedir):
        dirs = xbmcvfs.listdir(browsedir)[0]
        subdirs = [browsedir]
        for directory in dirs:
            directory = directory.decode("utf-8")
            cur_dir = "%s%s/" % (browsedir, directory)
            if recursive:
                subdirs.append(cur_dir)
            else:
                label = directory
                images.append((label, cur_dir, label2, "DefaultFolder.png"))
        for subdir in subdirs:
            for imagefile in xbmcvfs.listdir(subdir)[1]:
                imagefile = imagefile.decode("utf-8")
                label = imagefile
                imagepath = subdir + imagefile
                images.append((label, imagepath, label2, imagepath))
    return images 
Example #3
Source File: utils.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def unzip(path, dest, folder=None):

    ''' Unzip file. zipfile module seems to fail on android with badziperror.
    '''
    path = urllib.quote_plus(path)
    root = "zip://" + path + '/'
    
    if folder:

        xbmcvfs.mkdir(os.path.join(dest, folder))
        dest = os.path.join(dest, folder)
        root = get_zip_directory(root, folder)

    dirs, files = xbmcvfs.listdir(root)

    if dirs:
        unzip_recursive(root, dirs, dest)

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

    LOG.warn("Unzipped %s", path) 
Example #4
Source File: meta_players.py    From plugin.video.openmeta with GNU General Public License v3.0 6 votes vote down vote up
def get_players(media, filters={}):
	assert media in ('tvshows', 'movies')
	players = []
	players_path = 'special://profile/addon_data/plugin.video.openmeta/Players/'
	files = [x for x in xbmcvfs.listdir(players_path)[1] if x.endswith('.json')]
	for file in files:
		path = players_path + file
		try:
			f = xbmcvfs.File(path)
			try:
				content = f.read()
				meta = json.loads(content)
			finally:
				f.close()
			player = AddonPlayer(file, media, meta)
			if not player.is_empty():
				players.append(player)
		except:
			xbmcgui.Dialog().ok('Invalid player', 'player %s is invalid' % file)
	return sort_players(players, filters) 
Example #5
Source File: views.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def delete_nodes(self):

        ''' Remove node and children files.
        '''
        path = xbmc.translatePath("special://profile/library/video/").decode('utf-8')
        dirs, files = xbmcvfs.listdir(path)

        for file in files:

            if file.startswith('emby'):
                self.delete_node(os.path.join(path, file.decode('utf-8')))

        for directory in dirs:

            if directory.startswith('emby'):
                _, files = xbmcvfs.listdir(os.path.join(path, directory.decode('utf-8')))

                for file in files:
                    self.delete_node(os.path.join(path, directory.decode('utf-8'), file.decode('utf-8')))

                xbmcvfs.rmdir(os.path.join(path, directory.decode('utf-8'))) 
Example #6
Source File: vfs.py    From plugin.git.browser with GNU General Public License v3.0 6 votes vote down vote up
def ls(path, pattern=None, inlcude_path=False):
	try:
		if pattern:
			s = re.compile(pattern)
			folders = []
			files = []
			temp = xbmcvfs.listdir(path)
			for test in temp[0]:
				if s.search(str(test)):
					if inlcude_path: test = join(path, test)
					folders.append(test)
			for test in temp[1]:
				if s.search(str(test)):
					if inlcude_path: test = join(path, test)
					files.append(test)
			return [folders, files]
		else:
			return xbmcvfs.listdir(path)
	except Exception as e:
		xbmc.log('******** VFS error: %s' % e)
		return False 
Example #7
Source File: lib_tvshows.py    From plugin.video.openmeta with GNU General Public License v3.0 6 votes vote down vote up
def update_library():
	folder_path = plugin.get_setting('tv_library_folder', unicode)
	if not xbmcvfs.exists(folder_path):
		return
	library_folder = setup_library(folder_path)
	try:
		shows = xbmcvfs.listdir(library_folder)[0]
	except:
		shows = []
	clean_needed = False
	updated = 0
	for id in shows:
		try:
			id = int(id)
			with TVDB.session.cache_disabled():
				if add_tvshow_to_library(library_folder, TVDB[id]):
					clean_needed = True
		except:
			continue
		updated += 1
	if clean_needed:
		plugin.setProperty('plugin.video.openmeta.clean_library', 'true')
	if updated > 0:
		tools.scan_library(path=plugin.get_setting('tv_library_folder', unicode)) 
Example #8
Source File: utils.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def delete_folder(path=None):

    ''' Delete objects from kodi cache
    '''
    LOG.debug("--[ delete folder ]")
    delete_path = path is not None
    path = path or xbmc.translatePath('special://temp/emby').decode('utf-8')
    dirs, files = xbmcvfs.listdir(path)

    delete_recursive(path, dirs)

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

    if delete_path:
        xbmcvfs.delete(path)
    
    LOG.warn("DELETE %s", path) 
Example #9
Source File: kodi.py    From ru with GNU General Public License v2.0 6 votes vote down vote up
def get_play_count(filename):
    # Obtaining playback counter
    play_count = False
    if not filename or sqlite is None:
        return play_count

    # get path to database and determine videobase filename
    basepath = xbmc.translatePath("special://database")
    for basefile in xbmcvfs.listdir(basepath)[1]:
        if 'MyVideos' in basefile:
            videobase = basefile
            # connect to database
            db = sqlite.connect(os.path.join(basepath, videobase))
            try:
                sqlcur = db.execute('SELECT playCount FROM files WHERE strFilename like ?', ('%'+filename+'%',))
                res_playCount = sqlcur.fetchall()
                if res_playCount:
                    # check in the result data for at the least one played current file
                    if any(plcount > 0 for plcount in res_playCount):
                        play_count = True
            except:
                print 'Error connection to table file. Database is may be busy'
            db.close()

    return play_count 
Example #10
Source File: library_items.py    From plugin.video.netflix with MIT License 6 votes vote down vote up
def get_previously_exported_items():
    """Return a list of movie or tvshow VideoIds for items that were exported in
    the old storage format"""
    result = []
    videoid_pattern = re.compile('video_id=(\\d+)')
    for folder in _lib_folders(FOLDER_MOVIES) + _lib_folders(FOLDER_TV):
        for filename in xbmcvfs.listdir(folder)[1]:
            filepath = g.py2_decode(makeLegalFilename('/'.join([folder, filename])))
            if filepath.endswith('.strm'):
                common.debug('Trying to migrate {}', filepath)
                try:
                    # Only get a VideoId from the first file in each folder.
                    # For shows, all episodes will result in the same VideoId
                    # and movies only contain one file
                    result.append(
                        _get_root_videoid(filepath, videoid_pattern))
                except MetadataNotAvailable:
                    common.warn('Metadata not available, item skipped')
                except (AttributeError, IndexError):
                    common.warn('Item does not conform to old format')
                break
    return result 
Example #11
Source File: logging.py    From plugin.program.openwizard with GNU General Public License v3.0 6 votes vote down vote up
def grab_log(file=False, old=False, wizard=False):
    if wizard:
        if os.path.exists(CONFIG.WIZLOG):
            return CONFIG.WIZLOG if file else tools.read_from_file(CONFIG.WIZLOG)
        else:
            return False
                
    logsfound = []

    for item in [file for file in os.listdir(CONFIG.LOGPATH) if os.path.basename(file).startswith('kodi')]:
        if item.endswith('.log'):
            if (old and 'old' in item) or (not old and 'old' not in item):
                logsfound.append(os.path.join(CONFIG.LOGPATH, item))

    if len(logsfound) > 0:
        logsfound.sort(key=lambda f: os.path.getmtime(f))
        if file:
            return logsfound[-1]
        else:
            return tools.read_from_file(logsfound[-1])
    else:
        return False 
Example #12
Source File: menu.py    From plugin.program.openwizard with GNU General Public License v3.0 6 votes vote down vote up
def check_for_fm():
    if not xbmc.getCondVisibility('System.HasAddon(script.kodi.android.update)'):
        from resources.libs.gui import addon_menu
        addon_menu.install_from_kodi('script.kodi.android.update')
    
    try:
        updater = xbmcaddon.Addon('script.kodi.android.update')
    except RuntimeError as e:
        return False
        
    fm = int(updater.getSetting('File_Manager'))
    apps = xbmcvfs.listdir('androidapp://sources/apps/')[1]
    
    if fm == 0 and 'com.android.documentsui' not in apps:
        dialog = xbmcgui.Dialog()
        choose = dialog.yesno(CONFIG.ADDONTITLE, 'It appears your device has no default file manager. Would you like to set one now?')
        if not choose:
            dialog.ok(CONFIG.ADDONTITLE, 'If an APK downloads, but doesn\'t open for installation, try changing your file manager in {}\'s "Install Settings".'.format(CONFIG.ADDONTITLE))
        else:
            from resources.libs import install
            install.choose_file_manager()
            
    return True 
Example #13
Source File: Library.py    From plugin.video.netflix with MIT License 6 votes vote down vote up
def list_exported_media(self):
        """Return List of exported movies

        Returns
        -------
        obj:`dict`
            Contents of export folder
        """
        movies = (['', ''])
        shows = (['', ''])
        movie_path = self.movie_path
        tvshow_path = self.tvshow_path
        if xbmcvfs.exists(self.nx_common.check_folder_path(movie_path)):
            movies = xbmcvfs.listdir(movie_path)
        if xbmcvfs.exists(self.nx_common.check_folder_path(tvshow_path)):
            shows = xbmcvfs.listdir(tvshow_path)
        return movies + shows 
Example #14
Source File: context.py    From plugin.video.themoviedb.helper with GNU General Public License v3.0 6 votes vote down vote up
def library_getnfo_tmdbid(basedir=None, folder=None):
    """ Checks .nfo file and returns TMDB ID it contains """
    tmdb_id = None
    folder_list = xbmcvfs.listdir(basedir)[0]
    if folder in folder_list:
        nfo_folder = basedir + folder + '/'
        nfo = None
        for x in xbmcvfs.listdir(nfo_folder)[1]:
            if x.endswith('.nfo'):
                nfo = x
        if nfo:
            vfs_file = xbmcvfs.File(nfo_folder + nfo)
            content = ''
            try:
                content = vfs_file.read()
            finally:
                vfs_file.close()
            tmdb_id = content.replace('https://www.themoviedb.org/tv/', '')
            tmdb_id = tmdb_id.replace('&islocal=True', '')
    return tmdb_id 
Example #15
Source File: filetools.py    From addon with GNU General Public License v3.0 6 votes vote down vote up
def listdir(path, silent=False, vfs=True):
    """
    Lista un directorio
    @param path: Directorio a listar, debe ser un str "UTF-8"
    @type path: str
    @rtype: str
    @return: contenido de un directorio
    """

    path = encode(path)
    try:
        if xbmc_vfs and vfs:
            dirs, files = xbmcvfs.listdir(path)
            return dirs + files
        elif path.lower().startswith("smb://"):
            return decode(samba.listdir(path))
        else:
            return decode(os.listdir(path))
    except:
        logger.error("ERROR al leer el directorio: %s" % path)
        if not silent:
            logger.error(traceback.format_exc())
        return False 
Example #16
Source File: filetools.py    From addon with GNU General Public License v3.0 6 votes vote down vote up
def walk_vfs(top, topdown=True, onerror=None):
    """
    Lista un directorio de manera recursiva
    Como xmbcvfs no tiene esta función, se copia la lógica de libsmb(samba) para realizar la previa al Walk
    """
    top = encode(top)
    dirs, nondirs = xbmcvfs.listdir(top)

    if topdown:
        yield top, dirs, nondirs

    for name in dirs:
        if isinstance(name, unicode):
            name = name.encode("utf8")
            if PY3: name = name.decode("utf8")
        elif PY3 and isinstance(name, bytes):
            name = name.decode("utf8")
        elif not PY3:
            name = unicode(name, "utf8")
        new_path = "/".join(top.split("/") + [name])
        for x in walk_vfs(new_path, topdown, onerror):
            yield x
    if not topdown:
        yield top, dirs, nondirs 
Example #17
Source File: reporting.py    From script.artwork.beef with MIT License 6 votes vote down vote up
def _rotate_file():
    newdate = ndate = pykodi.get_infolabel('System.Date(yyyy-mm-dd)')
    count = 0
    while _exists(newdate):
        count += 1
        newdate = ndate + '.' + str(count)
    if not xbmcvfs.copy(_get_filepath(), _get_filepath(newdate)):
        log("Could not copy latest report to new filename", xbmc.LOGWARNING, 'reporting')
        return False
    if not xbmcvfs.delete(_get_filepath()):
        log("Could not delete old copy of latest report", xbmc.LOGWARNING, 'reporting')
        return False

    # delete old reports
    _, files = xbmcvfs.listdir(settings.datapath)
    reportfiles = sorted(f[:-4] for f in files if f.startswith(REPORT_NAME))
    while len(reportfiles) > REPORT_COUNT:
        filename = reportfiles[0] + '.txt'
        if not xbmcvfs.delete(settings.datapath + filename):
            log("Could not delete old report '{0}'".format(filename), xbmc.LOGWARNING, 'reporting')
            return False
        del reportfiles[0]
    report_startup()
    return True 
Example #18
Source File: artfiles.py    From script.artwork.beef with MIT License 6 votes vote down vote up
def getextra(self, path, exacttypes, thumbs=False):
        arttype = 'thumb' if thumbs else 'fanart'
        extradir = 'extrathumbs' if thumbs else 'extrafanart'
        sep = get_pathsep(path)
        missing, nextno = getopentypes(exacttypes, arttype)
        path += extradir + sep
        _, files = xbmcvfs.listdir(path)
        files.sort(key=natural_sort)
        result = {}
        for filename in files:
            check_filename = filename.lower()
            if not check_filename.endswith(ARTWORK_EXTS):
                continue
            popped = missing.pop(0) if missing else None
            nexttype = popped if popped else format_arttype(arttype, nextno)
            result[nexttype] = self.buildimage(path + filename, extradir + sep + filename)
            if not popped:
                nextno += 1
        return result 
Example #19
Source File: artfiles.py    From script.artwork.beef with MIT License 6 votes vote down vote up
def get_exact_images(self, mediaitem):
        path = find_central_infodir(mediaitem)
        if not path:
            return {}
        _, files = xbmcvfs.listdir(path)
        result = {}
        for filename in files:
            check_filename = filename.lower()
            if not check_filename.endswith(ARTWORK_EXTS):
                continue
            arttype = os.path.splitext(check_filename)[0]
            if not arttype.isalnum() or len(arttype) > ARTTYPE_MAXLENGTH:
                continue
            if settings.identify_alternatives and arttype in self.alttypes.keys():
                arttype = self.alttypes[arttype]
                if arttype in result.keys():
                    continue
            result[arttype] = self.buildimage(path + filename, filename, True)
        return result 
Example #20
Source File: main.py    From plugin.video.iptv.recorder with GNU General Public License v3.0 5 votes vote down vote up
def rmdirs(path):
    path = xbmc.translatePath(path)
    dirs, files = xbmcvfs.listdir(path)
    for dir in dirs:
        rmdirs(os.path.join(path,dir))
    xbmcvfs.rmdir(path) 
Example #21
Source File: main.py    From plugin.video.iptv.recorder with GNU General Public License v3.0 5 votes vote down vote up
def find_files(root):
    dirs, files = xbmcvfs.listdir(root)
    found_files = []
    for dir in dirs:
        path = os.path.join(xbmc.translatePath(root), dir)
        found_files = found_files + find_files(path)
    file_list = []
    for file in files:
        if file.endswith('.' + plugin.get_setting("ffmpeg.ext")):
            file = os.path.join(xbmc.translatePath(root), file)
            file_list.append(file)
    return found_files + file_list 
Example #22
Source File: resourceaddons.py    From script.skin.helper.service with GNU General Public License v2.0 5 votes vote down vote up
def get_multi_extension(filepath):
    '''check if resource addon or custom path has subfolders (multiimage)'''
    is_multi = False
    extension = ""
    dirs, files = xbmcvfs.listdir(filepath)
    if len(dirs) > 0:
        is_multi = True
    if not is_multi:
        for item in files:
            extension = "." + item.split(".")[-1]
            break
    return (is_multi, extension) 
Example #23
Source File: resourceaddons.py    From script.skin.helper.service with GNU General Public License v2.0 5 votes vote down vote up
def get_repo_resourceaddons(filterstr=""):
    '''helper to retrieve all available resource addons on the kodi repo'''
    result = []
    simplecache = SimpleCache()
    for item in xbmcvfs.listdir("addons://all/kodi.resource.images/")[1]:
        if not filterstr or item.lower().startswith(filterstr.lower()):
            addoninfo = get_repo_addoninfo(item, simplecache)
            if not addoninfo.get("name"):
                addoninfo = {"addonid": item, "name": item, "author": ""}
                addoninfo["thumbnail"] = "http://mirrors.kodi.tv/addons/krypton/%s/icon.png" % item
            addoninfo["path"] = "resource://%s/" % item
            result.append(addoninfo)
    simplecache.close()
    return result 
Example #24
Source File: filetools.py    From addon with GNU General Public License v3.0 5 votes vote down vote up
def isdir(path, silent=False, vfs=True):
    """
    Comprueba si la ruta es un directorio
    @param path: ruta
    @type path: str
    @rtype: bool
    @return: Retorna True si la ruta existe y es un directorio
    """
    path = encode(path)
    try:
        if xbmc_vfs and vfs:
            if not scrapertools.find_single_match(path, '(^\w+:\/\/)'):
                return os.path.isdir(path)
            if path.endswith('/') or path.endswith('\\'):
                path = path[:-1]
            dirs, files = xbmcvfs.listdir(dirname(path))
            base_name = basename(path)
            for dir in dirs:
                if base_name == dir:
                    return True
            return False
        elif path.lower().startswith("smb://"):
            return samba.isdir(path)
        else:
            return os.path.isdir(path)
    except:
        logger.error("ERROR al comprobar el directorio: %s" % path)
        if not silent:
            logger.error(traceback.format_exc())
        return False 
Example #25
Source File: service.py    From service.subtitles.subdivx with GNU General Public License v2.0 5 votes vote down vote up
def _handle_compressed_subs(workdir, compressed_file, ext):
    """
    Uncompress 'compressed_file' in 'workdir'.
    """
    if ext == 'rar' and kodi_major_version >= 18:
        src = 'archive' + '://' + quote_plus(compressed_file) + '/'
        (cdirs, cfiles) = xbmcvfs.listdir(src)
        for cfile in cfiles:
            fsrc = '%s%s' % (src, cfile)
            xbmcvfs.copy(fsrc, workdir + cfile)
    else:
        xbmc.executebuiltin("XBMC.Extract(%s, %s)" % (
                            compressed_file.encode("utf-8"),
                            workdir.encode("utf-8")), True)

    files = os.listdir(workdir)
    files = [f for f in files if is_subs_file(f)]
    found_files = []
    for fname in files:
        if not isinstance(fname, unicode):
            fname = fname.decode('utf-8')
        found_files.append({
            'forced': is_forced_subs_file(fname),
            'path': pjoin(workdir, fname)
        })
    if not found_files:
        log(u"Failed to unpack subtitles", level=LOGSEVERE)
    return found_files 
Example #26
Source File: filetools.py    From addon with GNU General Public License v3.0 5 votes vote down vote up
def isfile(path, silent=False, vfs=True):
    """
    Comprueba si la ruta es un fichero
    @param path: ruta
    @type path: str
    @rtype: bool
    @return: Retorna True si la ruta existe y es un archivo
    """
    path = encode(path)
    try:
        if xbmc_vfs and vfs:
            if not scrapertools.find_single_match(path, '(^\w+:\/\/)'):
                return os.path.isfile(path)
            if path.endswith('/') or path.endswith('\\'):
                path = path[:-1]
            dirs, files = xbmcvfs.listdir(dirname(path))
            base_name = basename(path)
            for file in files:
                if base_name == file:
                    return True
            return False
        elif path.lower().startswith("smb://"):
            return samba.isfile(path)
        else:
            return os.path.isfile(path)
    except:
        logger.error("ERROR al comprobar el archivo: %s" % path)
        if not silent:
            logger.error(traceback.format_exc())
        return False 
Example #27
Source File: utils.py    From plugin.video.surveillanceroom with GNU General Public License v3.0 5 votes vote down vote up
def remove_leftover_images(filename_prefix):
    """ Attempts to remove leftover images after player stops """
    xbmc.sleep(1000)
    for i in xbmcvfs.listdir(__data_path__)[1]:
        if filename_prefix in i:
            xbmcvfs.delete(os.path.join(__data_path__, i))
            log(4, 'CLEANUP IMAGES :: %s' %i) 
Example #28
Source File: mediainfo.py    From script.artwork.beef with MIT License 5 votes vote down vote up
def get_cached_listdir(path):
    return xbmcvfs.listdir(path) 
Example #29
Source File: artfiles.py    From script.artwork.beef with MIT License 5 votes vote down vote up
def get_exact_images(self, mediaitem):
        paths = (mediaitem.file, find_central_infodir(mediaitem))
        if not paths[0] and not paths[1]:
            return {}
        if settings.albumartwithmediafiles:
            paths = (paths[1], paths[0])
        if mediaitem.file:
            check_inputbase = os.path.splitext(os.path.basename(mediaitem.file))[0].lower()
        result = {}
        for path in paths:
            if not path:
                continue
            centraldir = path != mediaitem.file
            path = os.path.dirname(path) + get_pathsep(path)
            _, files = xbmcvfs.listdir(path)
            for filename in files:
                check_filename = filename.lower()
                if not check_filename.endswith(ARTWORK_EXTS):
                    continue
                basefile = os.path.splitext(check_filename)[0]
                if '-' not in basefile:
                    continue
                firstbit, arttype = basefile.rsplit('-', 1)
                if not arttype.isalnum():
                    continue
                if not centraldir and firstbit != check_inputbase:
                    continue
                if centraldir and firstbit not in (i.lower() for i in iter_possible_cleannames(mediaitem.label)):
                    continue
                result[arttype] = self.buildimage(path + filename, filename, centraldir)
        return result 
Example #30
Source File: service.py    From service.subtitles.subdivx with GNU General Public License v2.0 5 votes vote down vote up
def _cleanup_tempdirs(profile_path):
    dirs, _ = xbmcvfs.listdir(profile_path)
    total, ok = 0, 0
    for total, dir_path in enumerate(dirs[:10]):
        result = _cleanup_tempdir(os.path.join(profile_path, dir_path), verbose=False)
        if result:
            ok += 1
    log(u"Results: %d of %d dirs removed" % (ok, total + 1), level=LOGDEBUG)