RangeRequestWriter.cs 9.8 KB

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