StaticFileHandler.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Common.Logging;
  8. namespace MediaBrowser.Common.Net.Handlers
  9. {
  10. public class StaticFileHandler : BaseHandler
  11. {
  12. private string _Path;
  13. public virtual string Path
  14. {
  15. get
  16. {
  17. if (!string.IsNullOrWhiteSpace(_Path))
  18. {
  19. return _Path;
  20. }
  21. return QueryString["path"];
  22. }
  23. set
  24. {
  25. _Path = value;
  26. }
  27. }
  28. private bool _SourceStreamEnsured = false;
  29. private Stream _SourceStream = null;
  30. private Stream SourceStream
  31. {
  32. get
  33. {
  34. EnsureSourceStream();
  35. return _SourceStream;
  36. }
  37. }
  38. private void EnsureSourceStream()
  39. {
  40. if (!_SourceStreamEnsured)
  41. {
  42. try
  43. {
  44. _SourceStream = File.OpenRead(Path);
  45. }
  46. catch (FileNotFoundException ex)
  47. {
  48. StatusCode = 404;
  49. Logger.LogException(ex);
  50. }
  51. catch (DirectoryNotFoundException ex)
  52. {
  53. StatusCode = 404;
  54. Logger.LogException(ex);
  55. }
  56. catch (UnauthorizedAccessException ex)
  57. {
  58. StatusCode = 403;
  59. Logger.LogException(ex);
  60. }
  61. finally
  62. {
  63. _SourceStreamEnsured = true;
  64. }
  65. }
  66. }
  67. protected override bool SupportsByteRangeRequests
  68. {
  69. get
  70. {
  71. return true;
  72. }
  73. }
  74. public override bool ShouldCompressResponse(string contentType)
  75. {
  76. // Can't compress these
  77. if (IsRangeRequest)
  78. {
  79. return false;
  80. }
  81. // Don't compress media
  82. if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  83. {
  84. return false;
  85. }
  86. // It will take some work to support compression within this handler
  87. return false;
  88. }
  89. protected override long? GetTotalContentLength()
  90. {
  91. return SourceStream.Length;
  92. }
  93. protected override Task<DateTime?> GetLastDateModified()
  94. {
  95. DateTime? value = null;
  96. EnsureSourceStream();
  97. if (SourceStream != null)
  98. {
  99. value = File.GetLastWriteTime(Path);
  100. }
  101. return Task.FromResult<DateTime?>(value);
  102. }
  103. public override Task<string> GetContentType()
  104. {
  105. return Task.FromResult<string>(MimeTypes.GetMimeType(Path));
  106. }
  107. protected override Task PrepareResponse()
  108. {
  109. EnsureSourceStream();
  110. return Task.FromResult<object>(null);
  111. }
  112. protected override Task WriteResponseToOutputStream(Stream stream)
  113. {
  114. if (IsRangeRequest)
  115. {
  116. KeyValuePair<long, long?> requestedRange = RequestedRanges.First();
  117. // If the requested range is "0-" and we know the total length, we can optimize by avoiding having to buffer the content into memory
  118. if (requestedRange.Value == null && TotalContentLength != null)
  119. {
  120. return ServeCompleteRangeRequest(requestedRange, stream);
  121. }
  122. else if (TotalContentLength.HasValue)
  123. {
  124. // This will have to buffer a portion of the content into memory
  125. return ServePartialRangeRequestWithKnownTotalContentLength(requestedRange, stream);
  126. }
  127. else
  128. {
  129. // This will have to buffer the entire content into memory
  130. return ServePartialRangeRequestWithUnknownTotalContentLength(requestedRange, stream);
  131. }
  132. }
  133. else
  134. {
  135. return SourceStream.CopyToAsync(stream);
  136. }
  137. }
  138. protected override void DisposeResponseStream()
  139. {
  140. base.DisposeResponseStream();
  141. if (SourceStream != null)
  142. {
  143. SourceStream.Dispose();
  144. }
  145. }
  146. /// <summary>
  147. /// Handles a range request of "bytes=0-"
  148. /// This will serve the complete content and add the content-range header
  149. /// </summary>
  150. private Task ServeCompleteRangeRequest(KeyValuePair<long, long?> requestedRange, Stream responseStream)
  151. {
  152. long totalContentLength = TotalContentLength.Value;
  153. long rangeStart = requestedRange.Key;
  154. long rangeEnd = totalContentLength - 1;
  155. long rangeLength = 1 + rangeEnd - rangeStart;
  156. // Content-Length is the length of what we're serving, not the original content
  157. HttpListenerContext.Response.ContentLength64 = rangeLength;
  158. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  159. if (rangeStart > 0)
  160. {
  161. SourceStream.Position = rangeStart;
  162. }
  163. return SourceStream.CopyToAsync(responseStream);
  164. }
  165. /// <summary>
  166. /// Serves a partial range request where the total content length is not known
  167. /// </summary>
  168. private async Task ServePartialRangeRequestWithUnknownTotalContentLength(KeyValuePair<long, long?> requestedRange, Stream responseStream)
  169. {
  170. // Read the entire stream so that we can determine the length
  171. byte[] bytes = await ReadBytes(SourceStream, 0, null).ConfigureAwait(false);
  172. long totalContentLength = bytes.LongLength;
  173. long rangeStart = requestedRange.Key;
  174. long rangeEnd = requestedRange.Value ?? (totalContentLength - 1);
  175. long rangeLength = 1 + rangeEnd - rangeStart;
  176. // Content-Length is the length of what we're serving, not the original content
  177. HttpListenerContext.Response.ContentLength64 = rangeLength;
  178. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  179. await responseStream.WriteAsync(bytes, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength)).ConfigureAwait(false);
  180. }
  181. /// <summary>
  182. /// Serves a partial range request where the total content length is already known
  183. /// </summary>
  184. private async Task ServePartialRangeRequestWithKnownTotalContentLength(KeyValuePair<long, long?> requestedRange, Stream responseStream)
  185. {
  186. long totalContentLength = TotalContentLength.Value;
  187. long rangeStart = requestedRange.Key;
  188. long rangeEnd = requestedRange.Value ?? (totalContentLength - 1);
  189. long rangeLength = 1 + rangeEnd - rangeStart;
  190. // Only read the bytes we need
  191. byte[] bytes = await ReadBytes(SourceStream, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength)).ConfigureAwait(false);
  192. // Content-Length is the length of what we're serving, not the original content
  193. HttpListenerContext.Response.ContentLength64 = rangeLength;
  194. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  195. await responseStream.WriteAsync(bytes, 0, Convert.ToInt32(rangeLength)).ConfigureAwait(false);
  196. }
  197. /// <summary>
  198. /// Reads bytes from a stream
  199. /// </summary>
  200. /// <param name="input">The input stream</param>
  201. /// <param name="start">The starting position</param>
  202. /// <param name="count">The number of bytes to read, or null to read to the end.</param>
  203. private async Task<byte[]> ReadBytes(Stream input, int start, int? count)
  204. {
  205. if (start > 0)
  206. {
  207. input.Position = start;
  208. }
  209. if (count == null)
  210. {
  211. byte[] buffer = new byte[16 * 1024];
  212. using (MemoryStream ms = new MemoryStream())
  213. {
  214. int read;
  215. while ((read = await input.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
  216. {
  217. await ms.WriteAsync(buffer, 0, read).ConfigureAwait(false);
  218. }
  219. return ms.ToArray();
  220. }
  221. }
  222. else
  223. {
  224. byte[] buffer = new byte[count.Value];
  225. using (MemoryStream ms = new MemoryStream())
  226. {
  227. int read = await input.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
  228. await ms.WriteAsync(buffer, 0, read).ConfigureAwait(false);
  229. return ms.ToArray();
  230. }
  231. }
  232. }
  233. }
  234. }