RangeRequestWriter.cs 7.2 KB

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