StaticFileHandler.cs 9.5 KB

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