DirectoryService.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using MediaBrowser.Model.IO;
  5. namespace MediaBrowser.Controller.Providers
  6. {
  7. public class DirectoryService : IDirectoryService
  8. {
  9. private readonly IFileSystem _fileSystem;
  10. private readonly Dictionary<string, FileSystemMetadata[]> _cache = new Dictionary<string, FileSystemMetadata[]>(StringComparer.OrdinalIgnoreCase);
  11. private readonly Dictionary<string, FileSystemMetadata> _fileCache = new Dictionary<string, FileSystemMetadata>(StringComparer.OrdinalIgnoreCase);
  12. private readonly Dictionary<string, List<string>> _filePathCache = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
  13. public DirectoryService(IFileSystem fileSystem)
  14. {
  15. _fileSystem = fileSystem;
  16. }
  17. public FileSystemMetadata[] GetFileSystemEntries(string path)
  18. {
  19. if (!_cache.TryGetValue(path, out FileSystemMetadata[] entries))
  20. {
  21. entries = _fileSystem.GetFileSystemEntries(path).ToArray();
  22. _cache[path] = entries;
  23. }
  24. return entries;
  25. }
  26. public List<FileSystemMetadata> GetFiles(string path)
  27. {
  28. var list = new List<FileSystemMetadata>();
  29. var items = GetFileSystemEntries(path);
  30. foreach (var item in items)
  31. {
  32. if (!item.IsDirectory)
  33. {
  34. list.Add(item);
  35. }
  36. }
  37. return list;
  38. }
  39. public FileSystemMetadata GetFile(string path)
  40. {
  41. if (!_fileCache.TryGetValue(path, out FileSystemMetadata file))
  42. {
  43. file = _fileSystem.GetFileInfo(path);
  44. if (file != null && file.Exists)
  45. {
  46. _fileCache[path] = file;
  47. }
  48. else
  49. {
  50. return null;
  51. }
  52. }
  53. return file;
  54. }
  55. public IReadOnlyList<string> GetFilePaths(string path)
  56. => GetFilePaths(path, false);
  57. public IReadOnlyList<string> GetFilePaths(string path, bool clearCache)
  58. {
  59. if (clearCache || !_filePathCache.TryGetValue(path, out List<string> result))
  60. {
  61. result = _fileSystem.GetFilePaths(path).ToList();
  62. _filePathCache[path] = result;
  63. }
  64. return result;
  65. }
  66. }
  67. }