RangeRequestWriter.cs 9.3 KB

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