jellyfin/MediaBrowser.Controller/Providers/DirectoryService.cs

83 lines
2.5 KiB
C#
Raw Normal View History

using MediaBrowser.Model.Logging;
2014-02-11 22:41:01 +01:00
using System;
using System.Collections.Concurrent;
2014-02-08 23:38:02 +01:00
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MediaBrowser.Controller.Providers
{
2014-02-10 19:39:41 +01:00
public interface IDirectoryService
{
List<FileSystemInfo> GetFileSystemEntries(string path);
IEnumerable<FileSystemInfo> GetFiles(string path);
2014-05-08 07:04:39 +02:00
IEnumerable<FileSystemInfo> GetFiles(string path, bool clearCache);
FileSystemInfo GetFile(string path);
2014-02-10 19:39:41 +01:00
}
public class DirectoryService : IDirectoryService
2014-02-08 23:38:02 +01:00
{
private readonly ILogger _logger;
2014-02-15 17:36:09 +01:00
private readonly ConcurrentDictionary<string, List<FileSystemInfo>> _cache = new ConcurrentDictionary<string, List<FileSystemInfo>>(StringComparer.OrdinalIgnoreCase);
2014-02-08 23:38:02 +01:00
public DirectoryService(ILogger logger)
{
_logger = logger;
}
public List<FileSystemInfo> GetFileSystemEntries(string path)
2014-05-08 07:04:39 +02:00
{
return GetFileSystemEntries(path, false);
}
private List<FileSystemInfo> GetFileSystemEntries(string path, bool clearCache)
2014-02-08 23:38:02 +01:00
{
List<FileSystemInfo> entries;
2014-05-08 07:04:39 +02:00
if (clearCache)
{
List<FileSystemInfo> removed;
_cache.TryRemove(path, out removed);
}
2014-02-08 23:38:02 +01:00
if (!_cache.TryGetValue(path, out entries))
{
//_logger.Debug("Getting files for " + path);
2014-02-11 22:41:01 +01:00
try
{
entries = new DirectoryInfo(path).EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly).ToList();
}
catch (DirectoryNotFoundException)
{
entries = new List<FileSystemInfo>();
}
2014-02-15 17:36:09 +01:00
_cache.TryAdd(path, entries);
2014-02-08 23:38:02 +01:00
}
return entries;
}
public IEnumerable<FileSystemInfo> GetFiles(string path)
2014-02-08 23:38:02 +01:00
{
2014-05-08 07:04:39 +02:00
return GetFiles(path, false);
}
public IEnumerable<FileSystemInfo> GetFiles(string path, bool clearCache)
{
return GetFileSystemEntries(path, clearCache).Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory);
2014-02-08 23:38:02 +01:00
}
public FileSystemInfo GetFile(string path)
2014-02-08 23:38:02 +01:00
{
var directory = Path.GetDirectoryName(path);
var filename = Path.GetFileName(path);
return GetFiles(directory).FirstOrDefault(i => string.Equals(i.Name, filename, StringComparison.OrdinalIgnoreCase));
}
}
}