RangeRequestWriter.cs 7.2 KB

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