DirectoryService.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using MediaBrowser.Model.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 ConcurrentDictionary<string, FileSystemMetadata[]> _cache =
  16. new ConcurrentDictionary<string, FileSystemMetadata[]>(StringComparer.OrdinalIgnoreCase);
  17. private readonly ConcurrentDictionary<string, FileSystemMetadata> _fileCache =
  18. new ConcurrentDictionary<string, FileSystemMetadata>(StringComparer.OrdinalIgnoreCase);
  19. public DirectoryService(ILogger logger, IFileSystem fileSystem)
  20. {
  21. _logger = logger;
  22. _fileSystem = fileSystem;
  23. }
  24. public DirectoryService(IFileSystem fileSystem)
  25. : this(new NullLogger(), fileSystem)
  26. {
  27. }
  28. public FileSystemMetadata[] GetFileSystemEntries(string path)
  29. {
  30. return GetFileSystemEntries(path, false);
  31. }
  32. private FileSystemMetadata[] GetFileSystemEntries(string path, bool clearCache)
  33. {
  34. if (string.IsNullOrWhiteSpace(path))
  35. {
  36. throw new ArgumentNullException("path");
  37. }
  38. FileSystemMetadata[] entries;
  39. if (clearCache)
  40. {
  41. FileSystemMetadata[] removed;
  42. _cache.TryRemove(path, out removed);
  43. }
  44. if (!_cache.TryGetValue(path, out entries))
  45. {
  46. //_logger.Debug("Getting files for " + path);
  47. try
  48. {
  49. // using EnumerateFileSystemInfos doesn't handle reparse points (symlinks)
  50. entries = _fileSystem.GetFileSystemEntries(path).ToArray();
  51. }
  52. catch (IOException)
  53. {
  54. entries = new FileSystemMetadata[] { };
  55. }
  56. _cache.TryAdd(path, entries);
  57. }
  58. return entries;
  59. }
  60. public IEnumerable<FileSystemMetadata> GetFiles(string path)
  61. {
  62. return GetFiles(path, false);
  63. }
  64. public IEnumerable<FileSystemMetadata> GetFiles(string path, bool clearCache)
  65. {
  66. return GetFileSystemEntries(path, clearCache).Where(i => !i.IsDirectory);
  67. }
  68. public FileSystemMetadata GetFile(string path)
  69. {
  70. FileSystemMetadata file;
  71. if (!_fileCache.TryGetValue(path, out file))
  72. {
  73. file = _fileSystem.GetFileInfo(path);
  74. if (file != null && file.Exists)
  75. {
  76. _fileCache.TryAdd(path, file);
  77. }
  78. else
  79. {
  80. return null;
  81. }
  82. }
  83. return file;
  84. //return _fileSystem.GetFileInfo(path);
  85. }
  86. }
  87. }