RangeRequestWriter.cs 7.4 KB

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