FileWriter.cs 7.9 KB

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