123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- #pragma warning disable CS1591
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Linq;
- using MediaBrowser.Model.IO;
- namespace MediaBrowser.Controller.Providers
- {
- public class DirectoryService : IDirectoryService
- {
- // TODO make static and switch to FastConcurrentLru.
- private readonly ConcurrentDictionary<string, FileSystemMetadata[]> _cache = new(StringComparer.Ordinal);
- private readonly ConcurrentDictionary<string, FileSystemMetadata> _fileCache = new(StringComparer.Ordinal);
- private readonly ConcurrentDictionary<string, List<string>> _filePathCache = new(StringComparer.Ordinal);
- private readonly IFileSystem _fileSystem;
- public DirectoryService(IFileSystem fileSystem)
- {
- _fileSystem = fileSystem;
- }
- public FileSystemMetadata[] GetFileSystemEntries(string path)
- {
- return _cache.GetOrAdd(path, static (p, fileSystem) => fileSystem.GetFileSystemEntries(p).ToArray(), _fileSystem);
- }
- public List<FileSystemMetadata> GetDirectories(string path)
- {
- var list = new List<FileSystemMetadata>();
- var items = GetFileSystemEntries(path);
- for (var i = 0; i < items.Length; i++)
- {
- var item = items[i];
- if (item.IsDirectory)
- {
- list.Add(item);
- }
- }
- return list;
- }
- public List<FileSystemMetadata> GetFiles(string path)
- {
- var list = new List<FileSystemMetadata>();
- var items = GetFileSystemEntries(path);
- for (var i = 0; i < items.Length; i++)
- {
- var item = items[i];
- if (!item.IsDirectory)
- {
- list.Add(item);
- }
- }
- return list;
- }
- public FileSystemMetadata? GetFile(string path)
- {
- var entry = GetFileSystemEntry(path);
- return entry is not null && !entry.IsDirectory ? entry : null;
- }
- public FileSystemMetadata? GetDirectory(string path)
- {
- var entry = GetFileSystemEntry(path);
- return entry is not null && entry.IsDirectory ? entry : null;
- }
- public FileSystemMetadata? GetFileSystemEntry(string path)
- {
- if (!_fileCache.TryGetValue(path, out var result))
- {
- var file = _fileSystem.GetFileSystemInfo(path);
- if (file?.Exists ?? false)
- {
- result = file;
- _fileCache.TryAdd(path, result);
- }
- }
- return result;
- }
- public IReadOnlyList<string> GetFilePaths(string path)
- => GetFilePaths(path, false);
- public IReadOnlyList<string> GetFilePaths(string path, bool clearCache, bool sort = false)
- {
- if (clearCache)
- {
- _filePathCache.TryRemove(path, out _);
- }
- var filePaths = _filePathCache.GetOrAdd(path, static (p, fileSystem) => fileSystem.GetFilePaths(p).ToList(), _fileSystem);
- if (sort)
- {
- filePaths.Sort();
- }
- return filePaths;
- }
- public bool IsAccessible(string path)
- {
- return _fileSystem.GetFileSystemEntryPaths(path).Any();
- }
- }
- }
|