RangeRequestWriter.cs 9.5 KB

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