RangeRequestWriter.cs 6.8 KB

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