DirectoryService.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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) => fileSystem.GetFileSystemEntries(p).ToArray(), _fileSystem);
  22. }
  23. public List<FileSystemMetadata> GetFiles(string path)
  24. {
  25. var list = new List<FileSystemMetadata>();
  26. var items = GetFileSystemEntries(path);
  27. for (var i = 0; i < items.Length; i++)
  28. {
  29. var item = items[i];
  30. if (!item.IsDirectory)
  31. {
  32. list.Add(item);
  33. }
  34. }
  35. return list;
  36. }
  37. public FileSystemMetadata? GetFile(string path)
  38. {
  39. if (!_fileCache.TryGetValue(path, out var result))
  40. {
  41. var file = _fileSystem.GetFileInfo(path);
  42. if (file.Exists)
  43. {
  44. result = file;
  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, bool sort = false)
  53. {
  54. if (clearCache)
  55. {
  56. _filePathCache.TryRemove(path, out _);
  57. }
  58. var filePaths = _filePathCache.GetOrAdd(path, (p, fileSystem) => fileSystem.GetFilePaths(p).ToList(), _fileSystem);
  59. if (sort)
  60. {
  61. filePaths.Sort();
  62. }
  63. return filePaths;
  64. }
  65. }
  66. }