DirectoryService.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using Microsoft.Extensions.Logging;
  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 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. FileSystemMetadata[] entries;
  23. if (!_cache.TryGetValue(path, out entries))
  24. {
  25. //_logger.LogDebug("Getting files for " + path);
  26. entries = _fileSystem.GetFileSystemEntries(path).ToArray();
  27. //_cache.TryAdd(path, entries);
  28. _cache[path] = entries;
  29. }
  30. return entries;
  31. }
  32. public List<FileSystemMetadata> GetFiles(string path)
  33. {
  34. var list = new List<FileSystemMetadata>();
  35. var items = GetFileSystemEntries(path);
  36. foreach (var item in items)
  37. {
  38. if (!item.IsDirectory)
  39. {
  40. list.Add(item);
  41. }
  42. }
  43. return list;
  44. }
  45. public FileSystemMetadata GetFile(string path)
  46. {
  47. FileSystemMetadata file;
  48. if (!_fileCache.TryGetValue(path, out file))
  49. {
  50. file = _fileSystem.GetFileInfo(path);
  51. if (file != null && file.Exists)
  52. {
  53. //_fileCache.TryAdd(path, file);
  54. _fileCache[path] = file;
  55. }
  56. else
  57. {
  58. return null;
  59. }
  60. }
  61. return file;
  62. //return _fileSystem.GetFileInfo(path);
  63. }
  64. public List<string> GetFilePaths(string path)
  65. {
  66. return GetFilePaths(path, false);
  67. }
  68. public List<string> GetFilePaths(string path, bool clearCache)
  69. {
  70. List<string> result;
  71. if (clearCache || !_filePathCache.TryGetValue(path, out result))
  72. {
  73. result = _fileSystem.GetFilePaths(path).ToList();
  74. _filePathCache[path] = result;
  75. }
  76. return result;
  77. }
  78. }
  79. }