RangeRequestWriter.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. #pragma warning disable CS1591
  2. #pragma warning disable SA1600
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Net;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  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 RangeRequestWriter : IAsyncStreamWriter, IHttpResult
  16. {
  17. /// <summary>
  18. /// Gets or sets the source stream.
  19. /// </summary>
  20. /// <value>The source stream.</value>
  21. private Stream SourceStream { get; set; }
  22. private string RangeHeader { get; set; }
  23. private bool IsHeadRequest { get; set; }
  24. private long RangeStart { get; set; }
  25. private long RangeEnd { get; set; }
  26. private long RangeLength { get; set; }
  27. private long TotalContentLength { get; set; }
  28. public Action OnComplete { get; set; }
  29. private readonly ILogger _logger;
  30. private const int BufferSize = 81920;
  31. /// <summary>
  32. /// The _options
  33. /// </summary>
  34. private readonly Dictionary<string, string> _options = new Dictionary<string, string>();
  35. /// <summary>
  36. /// The us culture
  37. /// </summary>
  38. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  39. /// <summary>
  40. /// Additional HTTP Headers
  41. /// </summary>
  42. /// <value>The headers.</value>
  43. public IDictionary<string, string> Headers => _options;
  44. /// <summary>
  45. /// Initializes a new instance of the <see cref="RangeRequestWriter" /> class.
  46. /// </summary>
  47. /// <param name="rangeHeader">The range header.</param>
  48. /// <param name="contentLength">The content length.</param>
  49. /// <param name="source">The source.</param>
  50. /// <param name="contentType">Type of the content.</param>
  51. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  52. /// <param name="logger">The logger instance.</param>
  53. public RangeRequestWriter(string rangeHeader, long contentLength, Stream source, string contentType, bool isHeadRequest, ILogger logger)
  54. {
  55. if (string.IsNullOrEmpty(contentType))
  56. {
  57. throw new ArgumentNullException(nameof(contentType));
  58. }
  59. RangeHeader = rangeHeader;
  60. SourceStream = source;
  61. IsHeadRequest = isHeadRequest;
  62. this._logger = logger;
  63. ContentType = contentType;
  64. Headers[HeaderNames.ContentType] = contentType;
  65. Headers[HeaderNames.AcceptRanges] = "bytes";
  66. StatusCode = HttpStatusCode.PartialContent;
  67. SetRangeValues(contentLength);
  68. }
  69. /// <summary>
  70. /// Sets the range values.
  71. /// </summary>
  72. private void SetRangeValues(long contentLength)
  73. {
  74. var requestedRange = RequestedRanges[0];
  75. TotalContentLength = contentLength;
  76. // If the requested range is "0-", we can optimize by just doing a stream copy
  77. if (!requestedRange.Value.HasValue)
  78. {
  79. RangeEnd = TotalContentLength - 1;
  80. }
  81. else
  82. {
  83. RangeEnd = requestedRange.Value.Value;
  84. }
  85. RangeStart = requestedRange.Key;
  86. RangeLength = 1 + RangeEnd - RangeStart;
  87. Headers[HeaderNames.ContentLength] = RangeLength.ToString(CultureInfo.InvariantCulture);
  88. Headers[HeaderNames.ContentRange] = $"bytes {RangeStart}-{RangeEnd}/{TotalContentLength}";
  89. if (RangeStart > 0 && SourceStream.CanSeek)
  90. {
  91. SourceStream.Position = RangeStart;
  92. }
  93. }
  94. /// <summary>
  95. /// The _requested ranges
  96. /// </summary>
  97. private List<KeyValuePair<long, long?>> _requestedRanges;
  98. /// <summary>
  99. /// Gets the requested ranges.
  100. /// </summary>
  101. /// <value>The requested ranges.</value>
  102. protected List<KeyValuePair<long, long?>> RequestedRanges
  103. {
  104. get
  105. {
  106. if (_requestedRanges == null)
  107. {
  108. _requestedRanges = new List<KeyValuePair<long, long?>>();
  109. // Example: bytes=0-,32-63
  110. var ranges = RangeHeader.Split('=')[1].Split(',');
  111. foreach (var range in ranges)
  112. {
  113. var vals = range.Split('-');
  114. long start = 0;
  115. long? end = null;
  116. if (!string.IsNullOrEmpty(vals[0]))
  117. {
  118. start = long.Parse(vals[0], UsCulture);
  119. }
  120. if (!string.IsNullOrEmpty(vals[1]))
  121. {
  122. end = long.Parse(vals[1], UsCulture);
  123. }
  124. _requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
  125. }
  126. }
  127. return _requestedRanges;
  128. }
  129. }
  130. public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)
  131. {
  132. try
  133. {
  134. // Headers only
  135. if (IsHeadRequest)
  136. {
  137. return;
  138. }
  139. using (var source = SourceStream)
  140. {
  141. // If the requested range is "0-", we can optimize by just doing a stream copy
  142. if (RangeEnd >= TotalContentLength - 1)
  143. {
  144. await source.CopyToAsync(responseStream, BufferSize).ConfigureAwait(false);
  145. }
  146. else
  147. {
  148. await CopyToInternalAsync(source, responseStream, RangeLength).ConfigureAwait(false);
  149. }
  150. }
  151. }
  152. finally
  153. {
  154. if (OnComplete != null)
  155. {
  156. OnComplete();
  157. }
  158. }
  159. }
  160. private static async Task CopyToInternalAsync(Stream source, Stream destination, long copyLength)
  161. {
  162. var array = new byte[BufferSize];
  163. int bytesRead;
  164. while ((bytesRead = await source.ReadAsync(array, 0, array.Length).ConfigureAwait(false)) != 0)
  165. {
  166. if (bytesRead == 0)
  167. {
  168. break;
  169. }
  170. var bytesToCopy = Math.Min(bytesRead, copyLength);
  171. await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToCopy)).ConfigureAwait(false);
  172. copyLength -= bytesToCopy;
  173. if (copyLength <= 0)
  174. {
  175. break;
  176. }
  177. }
  178. }
  179. public string ContentType { get; set; }
  180. public IRequest RequestContext { get; set; }
  181. public object Response { get; set; }
  182. public int Status { get; set; }
  183. public HttpStatusCode StatusCode
  184. {
  185. get => (HttpStatusCode)Status;
  186. set => Status = (int)value;
  187. }
  188. }
  189. }