2
0

RangeRequestWriter.cs 7.7 KB

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