RangeRequestWriter.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. using ServiceStack.Service;
  2. using ServiceStack.ServiceHost;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Threading.Tasks;
  10. namespace MediaBrowser.Server.Implementations.HttpServer
  11. {
  12. public class RangeRequestWriter : IStreamWriter, IHttpResult
  13. {
  14. /// <summary>
  15. /// Gets or sets the source stream.
  16. /// </summary>
  17. /// <value>The source stream.</value>
  18. private Stream SourceStream { get; set; }
  19. private string RangeHeader { get; set; }
  20. private bool IsHeadRequest { get; set; }
  21. private long RangeStart { get; set; }
  22. private long RangeEnd { get; set; }
  23. private long RangeLength { get; set; }
  24. private long TotalContentLength { 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.First();
  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. var task = WriteToAsync(responseStream);
  140. Task.WaitAll(task);
  141. }
  142. /// <summary>
  143. /// Writes to async.
  144. /// </summary>
  145. /// <param name="responseStream">The response stream.</param>
  146. /// <returns>Task.</returns>
  147. private async Task WriteToAsync(Stream responseStream)
  148. {
  149. // Headers only
  150. if (IsHeadRequest)
  151. {
  152. return;
  153. }
  154. using (var source = SourceStream)
  155. {
  156. // If the requested range is "0-", we can optimize by just doing a stream copy
  157. if (RangeEnd == TotalContentLength - 1)
  158. {
  159. await source.CopyToAsync(responseStream).ConfigureAwait(false);
  160. }
  161. else
  162. {
  163. // Read the bytes we need
  164. var buffer = new byte[Convert.ToInt32(RangeLength)];
  165. await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
  166. await responseStream.WriteAsync(buffer, 0, Convert.ToInt32(RangeLength)).ConfigureAwait(false);
  167. }
  168. }
  169. }
  170. public string ContentType { get; set; }
  171. public IRequestContext RequestContext { get; set; }
  172. public object Response { get; set; }
  173. public IContentTypeWriter ResponseFilter { get; set; }
  174. public int Status { get; set; }
  175. public HttpStatusCode StatusCode
  176. {
  177. get { return (HttpStatusCode)Status; }
  178. set { Status = (int)value; }
  179. }
  180. public string StatusDescription { get; set; }
  181. }
  182. }