RangeRequestWriter.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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
  42. {
  43. get { return _options; }
  44. }
  45. /// <summary>
  46. /// Initializes a new instance of the <see cref="StreamWriter" /> class.
  47. /// </summary>
  48. /// <param name="rangeHeader">The range header.</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. 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("contentType");
  57. }
  58. RangeHeader = rangeHeader;
  59. SourceStream = source;
  60. IsHeadRequest = isHeadRequest;
  61. this._logger = logger;
  62. ContentType = contentType;
  63. Headers["Content-Type"] = contentType;
  64. Headers["Accept-Ranges"] = "bytes";
  65. StatusCode = HttpStatusCode.PartialContent;
  66. Cookies = new List<Cookie>();
  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. // Content-Length is the length of what we're serving, not the original content
  88. Headers["Content-Length"] = RangeLength.ToString(UsCulture);
  89. Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", RangeStart, RangeEnd, TotalContentLength);
  90. if (RangeStart > 0 && SourceStream.CanSeek)
  91. {
  92. SourceStream.Position = RangeStart;
  93. }
  94. }
  95. /// <summary>
  96. /// The _requested ranges
  97. /// </summary>
  98. private List<KeyValuePair<long, long?>> _requestedRanges;
  99. /// <summary>
  100. /// Gets the requested ranges.
  101. /// </summary>
  102. /// <value>The requested ranges.</value>
  103. protected List<KeyValuePair<long, long?>> RequestedRanges
  104. {
  105. get
  106. {
  107. if (_requestedRanges == null)
  108. {
  109. _requestedRanges = new List<KeyValuePair<long, long?>>();
  110. // Example: bytes=0-,32-63
  111. var ranges = RangeHeader.Split('=')[1].Split(',');
  112. foreach (var range in ranges)
  113. {
  114. var vals = range.Split('-');
  115. long start = 0;
  116. long? end = null;
  117. if (!string.IsNullOrEmpty(vals[0]))
  118. {
  119. start = long.Parse(vals[0], UsCulture);
  120. }
  121. if (!string.IsNullOrEmpty(vals[1]))
  122. {
  123. end = long.Parse(vals[1], UsCulture);
  124. }
  125. _requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
  126. }
  127. }
  128. return _requestedRanges;
  129. }
  130. }
  131. public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)
  132. {
  133. try
  134. {
  135. // Headers only
  136. if (IsHeadRequest)
  137. {
  138. return;
  139. }
  140. using (var source = SourceStream)
  141. {
  142. // If the requested range is "0-", we can optimize by just doing a stream copy
  143. if (RangeEnd >= TotalContentLength - 1)
  144. {
  145. await source.CopyToAsync(responseStream, BufferSize).ConfigureAwait(false);
  146. }
  147. else
  148. {
  149. await CopyToInternalAsync(source, responseStream, RangeLength).ConfigureAwait(false);
  150. }
  151. }
  152. }
  153. finally
  154. {
  155. if (OnComplete != null)
  156. {
  157. OnComplete();
  158. }
  159. }
  160. }
  161. private async Task CopyToInternalAsync(Stream source, Stream destination, long copyLength)
  162. {
  163. var array = new byte[BufferSize];
  164. int bytesRead;
  165. while ((bytesRead = await source.ReadAsync(array, 0, array.Length).ConfigureAwait(false)) != 0)
  166. {
  167. if (bytesRead == 0)
  168. {
  169. break;
  170. }
  171. var bytesToCopy = Math.Min(bytesRead, copyLength);
  172. await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToCopy)).ConfigureAwait(false);
  173. copyLength -= bytesToCopy;
  174. if (copyLength <= 0)
  175. {
  176. break;
  177. }
  178. }
  179. }
  180. public string ContentType { get; set; }
  181. public IRequest RequestContext { get; set; }
  182. public object Response { get; set; }
  183. public int Status { get; set; }
  184. public HttpStatusCode StatusCode
  185. {
  186. get { return (HttpStatusCode)Status; }
  187. set { Status = (int)value; }
  188. }
  189. public string StatusDescription { get; set; }
  190. }
  191. }