2
0

RangeRequestWriter.cs 7.7 KB

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