StaticFileHandler.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Kernel;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading.Tasks;
  9. namespace MediaBrowser.Common.Net.Handlers
  10. {
  11. /// <summary>
  12. /// Represents an http handler that serves static content
  13. /// </summary>
  14. public class StaticFileHandler : BaseHandler<IKernel>
  15. {
  16. /// <summary>
  17. /// Initializes a new instance of the <see cref="StaticFileHandler" /> class.
  18. /// </summary>
  19. /// <param name="kernel">The kernel.</param>
  20. public StaticFileHandler(IKernel kernel)
  21. {
  22. Initialize(kernel);
  23. }
  24. /// <summary>
  25. /// The _path
  26. /// </summary>
  27. private string _path;
  28. /// <summary>
  29. /// Gets or sets the path to the static resource
  30. /// </summary>
  31. /// <value>The path.</value>
  32. public string Path
  33. {
  34. get
  35. {
  36. if (!string.IsNullOrWhiteSpace(_path))
  37. {
  38. return _path;
  39. }
  40. return QueryString["path"];
  41. }
  42. set
  43. {
  44. _path = value;
  45. }
  46. }
  47. /// <summary>
  48. /// Gets or sets the last date modified of the resource
  49. /// </summary>
  50. /// <value>The last date modified.</value>
  51. public DateTime? LastDateModified { get; set; }
  52. /// <summary>
  53. /// Gets or sets the content type of the resource
  54. /// </summary>
  55. /// <value>The type of the content.</value>
  56. public string ContentType { get; set; }
  57. /// <summary>
  58. /// Gets or sets the content type of the resource
  59. /// </summary>
  60. /// <value>The etag.</value>
  61. public Guid Etag { get; set; }
  62. /// <summary>
  63. /// Gets or sets the source stream of the resource
  64. /// </summary>
  65. /// <value>The source stream.</value>
  66. public Stream SourceStream { get; set; }
  67. /// <summary>
  68. /// Shoulds the compress response.
  69. /// </summary>
  70. /// <param name="contentType">Type of the content.</param>
  71. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  72. private bool ShouldCompressResponse(string contentType)
  73. {
  74. // It will take some work to support compression with byte range requests
  75. if (IsRangeRequest)
  76. {
  77. return false;
  78. }
  79. // Don't compress media
  80. if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  81. {
  82. return false;
  83. }
  84. // Don't compress images
  85. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
  86. {
  87. return false;
  88. }
  89. return true;
  90. }
  91. /// <summary>
  92. /// Gets or sets the duration of the cache.
  93. /// </summary>
  94. /// <value>The duration of the cache.</value>
  95. public TimeSpan? CacheDuration { get; set; }
  96. /// <summary>
  97. /// Gets the total length of the content.
  98. /// </summary>
  99. /// <param name="responseInfo">The response info.</param>
  100. /// <returns>System.Nullable{System.Int64}.</returns>
  101. protected override long? GetTotalContentLength(ResponseInfo responseInfo)
  102. {
  103. // If we're compressing the response, content length must be the compressed length, which we don't know
  104. if (responseInfo.CompressResponse && ClientSupportsCompression)
  105. {
  106. return null;
  107. }
  108. return SourceStream.Length;
  109. }
  110. /// <summary>
  111. /// Gets the response info.
  112. /// </summary>
  113. /// <returns>Task{ResponseInfo}.</returns>
  114. protected override Task<ResponseInfo> GetResponseInfo()
  115. {
  116. var info = new ResponseInfo
  117. {
  118. ContentType = ContentType ?? MimeTypes.GetMimeType(Path),
  119. Etag = Etag,
  120. DateLastModified = LastDateModified
  121. };
  122. if (SourceStream == null && !string.IsNullOrEmpty(Path))
  123. {
  124. // FileShare must be ReadWrite in case someone else is currently writing to it.
  125. SourceStream = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous);
  126. }
  127. info.CompressResponse = ShouldCompressResponse(info.ContentType);
  128. info.SupportsByteRangeRequests = !info.CompressResponse || !ClientSupportsCompression;
  129. if (!info.DateLastModified.HasValue && !string.IsNullOrWhiteSpace(Path))
  130. {
  131. info.DateLastModified = File.GetLastWriteTimeUtc(Path);
  132. }
  133. if (CacheDuration.HasValue)
  134. {
  135. info.CacheDuration = CacheDuration.Value;
  136. }
  137. if (SourceStream == null && string.IsNullOrEmpty(Path))
  138. {
  139. throw new ResourceNotFoundException();
  140. }
  141. return Task.FromResult(info);
  142. }
  143. /// <summary>
  144. /// Writes the response to output stream.
  145. /// </summary>
  146. /// <param name="stream">The stream.</param>
  147. /// <param name="responseInfo">The response info.</param>
  148. /// <param name="totalContentLength">Total length of the content.</param>
  149. /// <returns>Task.</returns>
  150. protected override Task WriteResponseToOutputStream(Stream stream, ResponseInfo responseInfo, long? totalContentLength)
  151. {
  152. if (IsRangeRequest && totalContentLength.HasValue)
  153. {
  154. var requestedRange = RequestedRanges.First();
  155. // If the requested range is "0-", we can optimize by just doing a stream copy
  156. if (!requestedRange.Value.HasValue)
  157. {
  158. return ServeCompleteRangeRequest(requestedRange, stream, totalContentLength.Value);
  159. }
  160. // This will have to buffer a portion of the content into memory
  161. return ServePartialRangeRequest(requestedRange.Key, requestedRange.Value.Value, stream, totalContentLength.Value);
  162. }
  163. return SourceStream.CopyToAsync(stream);
  164. }
  165. /// <summary>
  166. /// Disposes the response stream.
  167. /// </summary>
  168. protected override void DisposeResponseStream()
  169. {
  170. if (SourceStream != null)
  171. {
  172. SourceStream.Dispose();
  173. }
  174. base.DisposeResponseStream();
  175. }
  176. /// <summary>
  177. /// Handles a range request of "bytes=0-"
  178. /// This will serve the complete content and add the content-range header
  179. /// </summary>
  180. /// <param name="requestedRange">The requested range.</param>
  181. /// <param name="responseStream">The response stream.</param>
  182. /// <param name="totalContentLength">Total length of the content.</param>
  183. /// <returns>Task.</returns>
  184. private Task ServeCompleteRangeRequest(KeyValuePair<long, long?> requestedRange, Stream responseStream, long totalContentLength)
  185. {
  186. var rangeStart = requestedRange.Key;
  187. var rangeEnd = totalContentLength - 1;
  188. var rangeLength = 1 + rangeEnd - rangeStart;
  189. // Content-Length is the length of what we're serving, not the original content
  190. HttpListenerContext.Response.ContentLength64 = rangeLength;
  191. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  192. if (rangeStart > 0)
  193. {
  194. SourceStream.Position = rangeStart;
  195. }
  196. return SourceStream.CopyToAsync(responseStream);
  197. }
  198. /// <summary>
  199. /// Serves a partial range request
  200. /// </summary>
  201. /// <param name="rangeStart">The range start.</param>
  202. /// <param name="rangeEnd">The range end.</param>
  203. /// <param name="responseStream">The response stream.</param>
  204. /// <param name="totalContentLength">Total length of the content.</param>
  205. /// <returns>Task.</returns>
  206. private async Task ServePartialRangeRequest(long rangeStart, long rangeEnd, Stream responseStream, long totalContentLength)
  207. {
  208. var rangeLength = 1 + rangeEnd - rangeStart;
  209. // Content-Length is the length of what we're serving, not the original content
  210. HttpListenerContext.Response.ContentLength64 = rangeLength;
  211. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  212. SourceStream.Position = rangeStart;
  213. // Fast track to just copy the stream to the end
  214. if (rangeEnd == totalContentLength - 1)
  215. {
  216. await SourceStream.CopyToAsync(responseStream).ConfigureAwait(false);
  217. }
  218. else
  219. {
  220. // Read the bytes we need
  221. var buffer = new byte[Convert.ToInt32(rangeLength)];
  222. await SourceStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
  223. await responseStream.WriteAsync(buffer, 0, Convert.ToInt32(rangeLength)).ConfigureAwait(false);
  224. }
  225. }
  226. }
  227. }