ResourceFileManager.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Net;
  6. using MediaBrowser.Model.IO;
  7. using MediaBrowser.Model.Services;
  8. using Microsoft.Extensions.Logging;
  9. namespace Emby.Server.Implementations
  10. {
  11. public class ResourceFileManager : IResourceFileManager
  12. {
  13. private readonly IFileSystem _fileSystem;
  14. private readonly ILogger _logger;
  15. private readonly IHttpResultFactory _resultFactory;
  16. public ResourceFileManager(
  17. IHttpResultFactory resultFactory,
  18. ILoggerFactory loggerFactory,
  19. IFileSystem fileSystem)
  20. {
  21. _resultFactory = resultFactory;
  22. _logger = loggerFactory.CreateLogger("ResourceManager");
  23. _fileSystem = fileSystem;
  24. }
  25. public Stream GetResourceFileStream(string basePath, string virtualPath)
  26. {
  27. return _fileSystem.GetFileStream(GetResourcePath(basePath, virtualPath), FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, true);
  28. }
  29. public Task<object> GetStaticFileResult(IRequest request, string basePath, string virtualPath, string contentType, TimeSpan? cacheDuration)
  30. {
  31. return _resultFactory.GetStaticFileResult(request, GetResourcePath(basePath, virtualPath));
  32. }
  33. public string ReadAllText(string basePath, string virtualPath)
  34. {
  35. return _fileSystem.ReadAllText(GetResourcePath(basePath, virtualPath));
  36. }
  37. private string GetResourcePath(string basePath, string virtualPath)
  38. {
  39. var fullPath = Path.Combine(basePath, virtualPath.Replace('/', _fileSystem.DirectorySeparatorChar));
  40. try
  41. {
  42. fullPath = _fileSystem.GetFullPath(fullPath);
  43. }
  44. catch (Exception ex)
  45. {
  46. _logger.LogError(ex, "Error in Path.GetFullPath");
  47. }
  48. // Don't allow file system access outside of the source folder
  49. if (!_fileSystem.ContainsSubPath(basePath, fullPath))
  50. {
  51. throw new SecurityException("Access denied");
  52. }
  53. return fullPath;
  54. }
  55. }
  56. }