DirectoryService.cs 2.2 KB

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