StaticFileHandler.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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 = false;
  33. private Stream _SourceStream = null;
  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<DateTime?>(value);
  106. }
  107. public override Task<string> GetContentType()
  108. {
  109. return Task.FromResult<string>(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. else if (TotalContentLength.HasValue)
  127. {
  128. // This will have to buffer a portion of the content into memory
  129. return ServePartialRangeRequestWithKnownTotalContentLength(requestedRange, stream);
  130. }
  131. else
  132. {
  133. // This will have to buffer the entire content into memory
  134. return ServePartialRangeRequestWithUnknownTotalContentLength(requestedRange, stream);
  135. }
  136. }
  137. else
  138. {
  139. return SourceStream.CopyToAsync(stream);
  140. }
  141. }
  142. protected override void DisposeResponseStream()
  143. {
  144. base.DisposeResponseStream();
  145. if (SourceStream != null)
  146. {
  147. SourceStream.Dispose();
  148. }
  149. }
  150. /// <summary>
  151. /// Handles a range request of "bytes=0-"
  152. /// This will serve the complete content and add the content-range header
  153. /// </summary>
  154. private Task ServeCompleteRangeRequest(KeyValuePair<long, long?> requestedRange, Stream responseStream)
  155. {
  156. long totalContentLength = TotalContentLength.Value;
  157. long rangeStart = requestedRange.Key;
  158. long rangeEnd = totalContentLength - 1;
  159. long rangeLength = 1 + rangeEnd - rangeStart;
  160. // Content-Length is the length of what we're serving, not the original content
  161. HttpListenerContext.Response.ContentLength64 = rangeLength;
  162. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  163. if (rangeStart > 0)
  164. {
  165. SourceStream.Position = rangeStart;
  166. }
  167. return SourceStream.CopyToAsync(responseStream);
  168. }
  169. /// <summary>
  170. /// Serves a partial range request where the total content length is not known
  171. /// </summary>
  172. private async Task ServePartialRangeRequestWithUnknownTotalContentLength(KeyValuePair<long, long?> requestedRange, Stream responseStream)
  173. {
  174. // Read the entire stream so that we can determine the length
  175. byte[] bytes = await ReadBytes(SourceStream, 0, null).ConfigureAwait(false);
  176. long totalContentLength = bytes.LongLength;
  177. long rangeStart = requestedRange.Key;
  178. long rangeEnd = requestedRange.Value ?? (totalContentLength - 1);
  179. long rangeLength = 1 + rangeEnd - rangeStart;
  180. // Content-Length is the length of what we're serving, not the original content
  181. HttpListenerContext.Response.ContentLength64 = rangeLength;
  182. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  183. await responseStream.WriteAsync(bytes, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength)).ConfigureAwait(false);
  184. }
  185. /// <summary>
  186. /// Serves a partial range request where the total content length is already known
  187. /// </summary>
  188. private async Task ServePartialRangeRequestWithKnownTotalContentLength(KeyValuePair<long, long?> requestedRange, Stream responseStream)
  189. {
  190. long totalContentLength = TotalContentLength.Value;
  191. long rangeStart = requestedRange.Key;
  192. long rangeEnd = requestedRange.Value ?? (totalContentLength - 1);
  193. long rangeLength = 1 + rangeEnd - rangeStart;
  194. // Only read the bytes we need
  195. byte[] bytes = await ReadBytes(SourceStream, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength)).ConfigureAwait(false);
  196. // Content-Length is the length of what we're serving, not the original content
  197. HttpListenerContext.Response.ContentLength64 = rangeLength;
  198. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  199. await responseStream.WriteAsync(bytes, 0, Convert.ToInt32(rangeLength)).ConfigureAwait(false);
  200. }
  201. /// <summary>
  202. /// Reads bytes from a stream
  203. /// </summary>
  204. /// <param name="input">The input stream</param>
  205. /// <param name="start">The starting position</param>
  206. /// <param name="count">The number of bytes to read, or null to read to the end.</param>
  207. private async Task<byte[]> ReadBytes(Stream input, int start, int? count)
  208. {
  209. if (start > 0)
  210. {
  211. input.Position = start;
  212. }
  213. if (count == null)
  214. {
  215. byte[] buffer = new byte[16 * 1024];
  216. using (MemoryStream ms = new MemoryStream())
  217. {
  218. int read;
  219. while ((read = await input.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
  220. {
  221. await ms.WriteAsync(buffer, 0, read).ConfigureAwait(false);
  222. }
  223. return ms.ToArray();
  224. }
  225. }
  226. else
  227. {
  228. byte[] buffer = new byte[count.Value];
  229. using (MemoryStream ms = new MemoryStream())
  230. {
  231. int read = await input.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
  232. await ms.WriteAsync(buffer, 0, read).ConfigureAwait(false);
  233. return ms.ToArray();
  234. }
  235. }
  236. }
  237. }
  238. }