DirectoryService.cs 3.0 KB

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