DirectoryService.cs 2.5 KB

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