FileWriter.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Emby.Server.Implementations.IO;
  9. using MediaBrowser.Model.IO;
  10. using MediaBrowser.Model.Services;
  11. using Microsoft.Extensions.Logging;
  12. using Microsoft.Net.Http.Headers;
  13. namespace Emby.Server.Implementations.HttpServer
  14. {
  15. public class FileWriter : IHttpResult
  16. {
  17. private readonly IStreamHelper _streamHelper;
  18. private ILogger Logger { get; set; }
  19. private readonly IFileSystem _fileSystem;
  20. private string RangeHeader { get; set; }
  21. private bool IsHeadRequest { get; set; }
  22. private long RangeStart { get; set; }
  23. private long RangeEnd { get; set; }
  24. private long RangeLength { get; set; }
  25. public long TotalContentLength { get; set; }
  26. public Action OnComplete { get; set; }
  27. public Action OnError { get; set; }
  28. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  29. public List<Cookie> Cookies { get; private set; }
  30. public FileShareMode FileShare { get; set; }
  31. /// <summary>
  32. /// The _options
  33. /// </summary>
  34. private readonly IDictionary<string, string> _options = new Dictionary<string, string>();
  35. /// <summary>
  36. /// Gets the options.
  37. /// </summary>
  38. /// <value>The options.</value>
  39. public IDictionary<string, string> Headers => _options;
  40. public string Path { get; set; }
  41. public FileWriter(string path, string contentType, string rangeHeader, ILogger logger, IFileSystem fileSystem, IStreamHelper streamHelper)
  42. {
  43. if (string.IsNullOrEmpty(contentType))
  44. {
  45. throw new ArgumentNullException(nameof(contentType));
  46. }
  47. _streamHelper = streamHelper;
  48. _fileSystem = fileSystem;
  49. Path = path;
  50. Logger = logger;
  51. RangeHeader = rangeHeader;
  52. Headers[HeaderNames.ContentType] = contentType;
  53. TotalContentLength = fileSystem.GetFileInfo(path).Length;
  54. Headers[HeaderNames.AcceptRanges] = "bytes";
  55. if (string.IsNullOrWhiteSpace(rangeHeader))
  56. {
  57. StatusCode = HttpStatusCode.OK;
  58. }
  59. else
  60. {
  61. StatusCode = HttpStatusCode.PartialContent;
  62. SetRangeValues();
  63. }
  64. FileShare = FileShareMode.Read;
  65. Cookies = new List<Cookie>();
  66. }
  67. /// <summary>
  68. /// Sets the range values.
  69. /// </summary>
  70. private void SetRangeValues()
  71. {
  72. var requestedRange = RequestedRanges[0];
  73. // If the requested range is "0-", we can optimize by just doing a stream copy
  74. if (!requestedRange.Value.HasValue)
  75. {
  76. RangeEnd = TotalContentLength - 1;
  77. }
  78. else
  79. {
  80. RangeEnd = requestedRange.Value.Value;
  81. }
  82. RangeStart = requestedRange.Key;
  83. RangeLength = 1 + RangeEnd - RangeStart;
  84. var rangeString = $"bytes {RangeStart}-{RangeEnd}/{TotalContentLength}";
  85. Headers[HeaderNames.ContentRange] = rangeString;
  86. Logger.LogInformation("Setting range response values for {0}. RangeRequest: {1} Content-Range: {2}", Path, RangeHeader, rangeString);
  87. }
  88. /// <summary>
  89. /// The _requested ranges
  90. /// </summary>
  91. private List<KeyValuePair<long, long?>> _requestedRanges;
  92. /// <summary>
  93. /// Gets the requested ranges.
  94. /// </summary>
  95. /// <value>The requested ranges.</value>
  96. protected List<KeyValuePair<long, long?>> RequestedRanges
  97. {
  98. get
  99. {
  100. if (_requestedRanges == null)
  101. {
  102. _requestedRanges = new List<KeyValuePair<long, long?>>();
  103. // Example: bytes=0-,32-63
  104. var ranges = RangeHeader.Split('=')[1].Split(',');
  105. foreach (var range in ranges)
  106. {
  107. var vals = range.Split('-');
  108. long start = 0;
  109. long? end = null;
  110. if (!string.IsNullOrEmpty(vals[0]))
  111. {
  112. start = long.Parse(vals[0], UsCulture);
  113. }
  114. if (!string.IsNullOrEmpty(vals[1]))
  115. {
  116. end = long.Parse(vals[1], UsCulture);
  117. }
  118. _requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
  119. }
  120. }
  121. return _requestedRanges;
  122. }
  123. }
  124. private static readonly string[] SkipLogExtensions = {
  125. ".js",
  126. ".html",
  127. ".css"
  128. };
  129. public async Task WriteToAsync(IResponse response, CancellationToken cancellationToken)
  130. {
  131. try
  132. {
  133. // Headers only
  134. if (IsHeadRequest)
  135. {
  136. return;
  137. }
  138. var path = Path;
  139. var offset = RangeStart;
  140. var count = RangeLength;
  141. if (string.IsNullOrWhiteSpace(RangeHeader) || RangeStart <= 0 && RangeEnd >= TotalContentLength - 1)
  142. {
  143. var extension = System.IO.Path.GetExtension(path);
  144. if (extension == null || !SkipLogExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
  145. {
  146. Logger.LogDebug("Transmit file {0}", path);
  147. }
  148. offset = 0;
  149. count = 0;
  150. }
  151. await response.TransmitFile(path, offset, count, FileShare, _fileSystem, _streamHelper, cancellationToken).ConfigureAwait(false);
  152. }
  153. finally
  154. {
  155. OnComplete?.Invoke();
  156. }
  157. }
  158. public string ContentType { get; set; }
  159. public IRequest RequestContext { get; set; }
  160. public object Response { get; set; }
  161. public int Status { get; set; }
  162. public HttpStatusCode StatusCode
  163. {
  164. get => (HttpStatusCode)Status;
  165. set => Status = (int)value;
  166. }
  167. }
  168. }