2
0

StaticFileHandler.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 Stream SourceStream { get; set; }
  33. protected override bool SupportsByteRangeRequests
  34. {
  35. get
  36. {
  37. return true;
  38. }
  39. }
  40. private bool ShouldCompressResponse(string contentType)
  41. {
  42. // Can't compress these
  43. if (IsRangeRequest)
  44. {
  45. return false;
  46. }
  47. // Don't compress media
  48. if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  49. {
  50. return false;
  51. }
  52. // It will take some work to support compression within this handler
  53. return false;
  54. }
  55. protected override long? GetTotalContentLength()
  56. {
  57. return SourceStream.Length;
  58. }
  59. protected override Task<ResponseInfo> GetResponseInfo()
  60. {
  61. ResponseInfo info = new ResponseInfo
  62. {
  63. ContentType = MimeTypes.GetMimeType(Path),
  64. };
  65. try
  66. {
  67. SourceStream = File.OpenRead(Path);
  68. }
  69. catch (FileNotFoundException ex)
  70. {
  71. info.StatusCode = 404;
  72. Logger.LogException(ex);
  73. }
  74. catch (DirectoryNotFoundException ex)
  75. {
  76. info.StatusCode = 404;
  77. Logger.LogException(ex);
  78. }
  79. catch (UnauthorizedAccessException ex)
  80. {
  81. info.StatusCode = 403;
  82. Logger.LogException(ex);
  83. }
  84. info.CompressResponse = ShouldCompressResponse(info.ContentType);
  85. if (SourceStream != null)
  86. {
  87. info.DateLastModified = File.GetLastWriteTimeUtc(Path);
  88. }
  89. return Task.FromResult<ResponseInfo>(info);
  90. }
  91. protected override Task WriteResponseToOutputStream(Stream stream)
  92. {
  93. if (IsRangeRequest)
  94. {
  95. KeyValuePair<long, long?> requestedRange = RequestedRanges.First();
  96. // If the requested range is "0-" and we know the total length, we can optimize by avoiding having to buffer the content into memory
  97. if (requestedRange.Value == null && TotalContentLength != null)
  98. {
  99. return ServeCompleteRangeRequest(requestedRange, stream);
  100. }
  101. if (TotalContentLength.HasValue)
  102. {
  103. // This will have to buffer a portion of the content into memory
  104. return ServePartialRangeRequestWithKnownTotalContentLength(requestedRange, stream);
  105. }
  106. // This will have to buffer the entire content into memory
  107. return ServePartialRangeRequestWithUnknownTotalContentLength(requestedRange, stream);
  108. }
  109. return SourceStream.CopyToAsync(stream);
  110. }
  111. protected override void DisposeResponseStream()
  112. {
  113. base.DisposeResponseStream();
  114. if (SourceStream != null)
  115. {
  116. SourceStream.Dispose();
  117. }
  118. }
  119. /// <summary>
  120. /// Handles a range request of "bytes=0-"
  121. /// This will serve the complete content and add the content-range header
  122. /// </summary>
  123. private Task ServeCompleteRangeRequest(KeyValuePair<long, long?> requestedRange, Stream responseStream)
  124. {
  125. long totalContentLength = TotalContentLength.Value;
  126. long rangeStart = requestedRange.Key;
  127. long rangeEnd = totalContentLength - 1;
  128. long rangeLength = 1 + rangeEnd - rangeStart;
  129. // Content-Length is the length of what we're serving, not the original content
  130. HttpListenerContext.Response.ContentLength64 = rangeLength;
  131. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  132. if (rangeStart > 0)
  133. {
  134. SourceStream.Position = rangeStart;
  135. }
  136. return SourceStream.CopyToAsync(responseStream);
  137. }
  138. /// <summary>
  139. /// Serves a partial range request where the total content length is not known
  140. /// </summary>
  141. private async Task ServePartialRangeRequestWithUnknownTotalContentLength(KeyValuePair<long, long?> requestedRange, Stream responseStream)
  142. {
  143. // Read the entire stream so that we can determine the length
  144. byte[] bytes = await ReadBytes(SourceStream, 0, null).ConfigureAwait(false);
  145. long totalContentLength = bytes.LongLength;
  146. long rangeStart = requestedRange.Key;
  147. long rangeEnd = requestedRange.Value ?? (totalContentLength - 1);
  148. long rangeLength = 1 + rangeEnd - rangeStart;
  149. // Content-Length is the length of what we're serving, not the original content
  150. HttpListenerContext.Response.ContentLength64 = rangeLength;
  151. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  152. await responseStream.WriteAsync(bytes, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength)).ConfigureAwait(false);
  153. }
  154. /// <summary>
  155. /// Serves a partial range request where the total content length is already known
  156. /// </summary>
  157. private async Task ServePartialRangeRequestWithKnownTotalContentLength(KeyValuePair<long, long?> requestedRange, Stream responseStream)
  158. {
  159. long totalContentLength = TotalContentLength.Value;
  160. long rangeStart = requestedRange.Key;
  161. long rangeEnd = requestedRange.Value ?? (totalContentLength - 1);
  162. long rangeLength = 1 + rangeEnd - rangeStart;
  163. // Only read the bytes we need
  164. byte[] bytes = await ReadBytes(SourceStream, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength)).ConfigureAwait(false);
  165. // Content-Length is the length of what we're serving, not the original content
  166. HttpListenerContext.Response.ContentLength64 = rangeLength;
  167. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  168. await responseStream.WriteAsync(bytes, 0, Convert.ToInt32(rangeLength)).ConfigureAwait(false);
  169. }
  170. /// <summary>
  171. /// Reads bytes from a stream
  172. /// </summary>
  173. /// <param name="input">The input stream</param>
  174. /// <param name="start">The starting position</param>
  175. /// <param name="count">The number of bytes to read, or null to read to the end.</param>
  176. private async Task<byte[]> ReadBytes(Stream input, int start, int? count)
  177. {
  178. if (start > 0)
  179. {
  180. input.Position = start;
  181. }
  182. if (count == null)
  183. {
  184. var buffer = new byte[16 * 1024];
  185. using (var ms = new MemoryStream())
  186. {
  187. int read;
  188. while ((read = await input.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
  189. {
  190. await ms.WriteAsync(buffer, 0, read).ConfigureAwait(false);
  191. }
  192. return ms.ToArray();
  193. }
  194. }
  195. else
  196. {
  197. var buffer = new byte[count.Value];
  198. using (var ms = new MemoryStream())
  199. {
  200. int read = await input.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
  201. await ms.WriteAsync(buffer, 0, read).ConfigureAwait(false);
  202. return ms.ToArray();
  203. }
  204. }
  205. }
  206. }
  207. }