RangeRequestWriter.cs 9.6 KB

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