DirectoryService.cs 2.8 KB

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