RangeRequestWriter.cs 9.5 KB

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