FileWriter.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Runtime.InteropServices;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using MediaBrowser.Model.IO;
  12. using MediaBrowser.Model.Services;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.Extensions.Logging;
  15. using Microsoft.Net.Http.Headers;
  16. namespace Emby.Server.Implementations.HttpServer
  17. {
  18. public class FileWriter : IHttpResult
  19. {
  20. private static readonly CultureInfo UsCulture = CultureInfo.ReadOnly(new CultureInfo("en-US"));
  21. private static readonly string[] _skipLogExtensions = {
  22. ".js",
  23. ".html",
  24. ".css"
  25. };
  26. private readonly IStreamHelper _streamHelper;
  27. private readonly ILogger _logger;
  28. private readonly IFileSystem _fileSystem;
  29. /// <summary>
  30. /// The _options.
  31. /// </summary>
  32. private readonly IDictionary<string, string> _options = new Dictionary<string, string>();
  33. /// <summary>
  34. /// The _requested ranges.
  35. /// </summary>
  36. private List<KeyValuePair<long, long?>> _requestedRanges;
  37. public FileWriter(string path, string contentType, string rangeHeader, ILogger logger, IFileSystem fileSystem, IStreamHelper streamHelper)
  38. {
  39. if (string.IsNullOrEmpty(contentType))
  40. {
  41. throw new ArgumentNullException(nameof(contentType));
  42. }
  43. _streamHelper = streamHelper;
  44. _fileSystem = fileSystem;
  45. Path = path;
  46. _logger = logger;
  47. RangeHeader = rangeHeader;
  48. Headers[HeaderNames.ContentType] = contentType;
  49. TotalContentLength = fileSystem.GetFileInfo(path).Length;
  50. Headers[HeaderNames.AcceptRanges] = "bytes";
  51. if (string.IsNullOrWhiteSpace(rangeHeader))
  52. {
  53. Headers[HeaderNames.ContentLength] = TotalContentLength.ToString(CultureInfo.InvariantCulture);
  54. StatusCode = HttpStatusCode.OK;
  55. }
  56. else
  57. {
  58. StatusCode = HttpStatusCode.PartialContent;
  59. SetRangeValues();
  60. }
  61. FileShare = FileShare.Read;
  62. Cookies = new List<Cookie>();
  63. }
  64. private string RangeHeader { get; set; }
  65. private bool IsHeadRequest { get; set; }
  66. private long RangeStart { get; set; }
  67. private long RangeEnd { get; set; }
  68. private long RangeLength { get; set; }
  69. public long TotalContentLength { get; set; }
  70. public Action OnComplete { get; set; }
  71. public Action OnError { get; set; }
  72. public List<Cookie> Cookies { get; private set; }
  73. public FileShare FileShare { get; set; }
  74. /// <summary>
  75. /// Gets the options.
  76. /// </summary>
  77. /// <value>The options.</value>
  78. public IDictionary<string, string> Headers => _options;
  79. public string Path { get; set; }
  80. /// <summary>
  81. /// Gets the requested ranges.
  82. /// </summary>
  83. /// <value>The requested ranges.</value>
  84. protected List<KeyValuePair<long, long?>> RequestedRanges
  85. {
  86. get
  87. {
  88. if (_requestedRanges == null)
  89. {
  90. _requestedRanges = new List<KeyValuePair<long, long?>>();
  91. // Example: bytes=0-,32-63
  92. var ranges = RangeHeader.Split('=')[1].Split(',');
  93. foreach (var range in ranges)
  94. {
  95. var vals = range.Split('-');
  96. long start = 0;
  97. long? end = null;
  98. if (!string.IsNullOrEmpty(vals[0]))
  99. {
  100. start = long.Parse(vals[0], UsCulture);
  101. }
  102. if (!string.IsNullOrEmpty(vals[1]))
  103. {
  104. end = long.Parse(vals[1], UsCulture);
  105. }
  106. _requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
  107. }
  108. }
  109. return _requestedRanges;
  110. }
  111. }
  112. public string ContentType { get; set; }
  113. public IRequest RequestContext { get; set; }
  114. public object Response { get; set; }
  115. public int Status { get; set; }
  116. public HttpStatusCode StatusCode
  117. {
  118. get => (HttpStatusCode)Status;
  119. set => Status = (int)value;
  120. }
  121. /// <summary>
  122. /// Sets the range values.
  123. /// </summary>
  124. private void SetRangeValues()
  125. {
  126. var requestedRange = RequestedRanges[0];
  127. // If the requested range is "0-", we can optimize by just doing a stream copy
  128. if (!requestedRange.Value.HasValue)
  129. {
  130. RangeEnd = TotalContentLength - 1;
  131. }
  132. else
  133. {
  134. RangeEnd = requestedRange.Value.Value;
  135. }
  136. RangeStart = requestedRange.Key;
  137. RangeLength = 1 + RangeEnd - RangeStart;
  138. // Content-Length is the length of what we're serving, not the original content
  139. var lengthString = RangeLength.ToString(CultureInfo.InvariantCulture);
  140. Headers[HeaderNames.ContentLength] = lengthString;
  141. var rangeString = $"bytes {RangeStart}-{RangeEnd}/{TotalContentLength}";
  142. Headers[HeaderNames.ContentRange] = rangeString;
  143. _logger.LogDebug("Setting range response values for {0}. RangeRequest: {1} Content-Length: {2}, Content-Range: {3}", Path, RangeHeader, lengthString, rangeString);
  144. }
  145. public async Task WriteToAsync(HttpResponse response, CancellationToken cancellationToken)
  146. {
  147. try
  148. {
  149. // Headers only
  150. if (IsHeadRequest)
  151. {
  152. return;
  153. }
  154. var path = Path;
  155. var offset = RangeStart;
  156. var count = RangeLength;
  157. if (string.IsNullOrWhiteSpace(RangeHeader) || RangeStart <= 0 && RangeEnd >= TotalContentLength - 1)
  158. {
  159. var extension = System.IO.Path.GetExtension(path);
  160. if (extension == null || !_skipLogExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
  161. {
  162. _logger.LogDebug("Transmit file {0}", path);
  163. }
  164. offset = 0;
  165. count = 0;
  166. }
  167. await TransmitFile(response.Body, path, offset, count, FileShare, cancellationToken).ConfigureAwait(false);
  168. }
  169. finally
  170. {
  171. OnComplete?.Invoke();
  172. }
  173. }
  174. public async Task TransmitFile(Stream stream, string path, long offset, long count, FileShare fileShare, CancellationToken cancellationToken)
  175. {
  176. var fileOptions = FileOptions.SequentialScan;
  177. // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
  178. if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  179. {
  180. fileOptions |= FileOptions.Asynchronous;
  181. }
  182. using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, fileShare, IODefaults.FileStreamBufferSize, fileOptions))
  183. {
  184. if (offset > 0)
  185. {
  186. fs.Position = offset;
  187. }
  188. if (count > 0)
  189. {
  190. await _streamHelper.CopyToAsync(fs, stream, count, cancellationToken).ConfigureAwait(false);
  191. }
  192. else
  193. {
  194. await fs.CopyToAsync(stream, IODefaults.CopyToBufferSize, cancellationToken).ConfigureAwait(false);
  195. }
  196. }
  197. }
  198. }
  199. }