StaticFileHandler.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 CompressResponse
  75. {
  76. get
  77. {
  78. // Can't compress these
  79. if (IsRangeRequest)
  80. {
  81. return false;
  82. }
  83. string contentType = ContentType;
  84. // Don't compress media
  85. if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  86. {
  87. return false;
  88. }
  89. // It will take some work to support compression within this handler
  90. return false;
  91. }
  92. }
  93. protected override long? GetTotalContentLength()
  94. {
  95. return SourceStream.Length;
  96. }
  97. protected override DateTime? GetLastDateModified()
  98. {
  99. EnsureSourceStream();
  100. if (SourceStream == null)
  101. {
  102. return null;
  103. }
  104. return File.GetLastWriteTime(Path);
  105. }
  106. public override string ContentType
  107. {
  108. get
  109. {
  110. return MimeTypes.GetMimeType(Path);
  111. }
  112. }
  113. protected override void PrepareResponse()
  114. {
  115. base.PrepareResponse();
  116. EnsureSourceStream();
  117. }
  118. protected async override Task WriteResponseToOutputStream(Stream stream)
  119. {
  120. if (IsRangeRequest)
  121. {
  122. KeyValuePair<long, long?> requestedRange = RequestedRanges.First();
  123. // If the requested range is "0-" and we know the total length, we can optimize by avoiding having to buffer the content into memory
  124. if (requestedRange.Value == null && TotalContentLength != null)
  125. {
  126. await ServeCompleteRangeRequest(requestedRange, stream);
  127. }
  128. else if (TotalContentLength.HasValue)
  129. {
  130. // This will have to buffer a portion of the content into memory
  131. await ServePartialRangeRequestWithKnownTotalContentLength(requestedRange, stream);
  132. }
  133. else
  134. {
  135. // This will have to buffer the entire content into memory
  136. await ServePartialRangeRequestWithUnknownTotalContentLength(requestedRange, stream);
  137. }
  138. }
  139. else
  140. {
  141. await SourceStream.CopyToAsync(stream);
  142. }
  143. }
  144. protected override void DisposeResponseStream()
  145. {
  146. base.DisposeResponseStream();
  147. if (SourceStream != null)
  148. {
  149. SourceStream.Dispose();
  150. }
  151. }
  152. /// <summary>
  153. /// Handles a range request of "bytes=0-"
  154. /// This will serve the complete content and add the content-range header
  155. /// </summary>
  156. private async Task ServeCompleteRangeRequest(KeyValuePair<long, long?> requestedRange, Stream responseStream)
  157. {
  158. long totalContentLength = TotalContentLength.Value;
  159. long rangeStart = requestedRange.Key;
  160. long rangeEnd = totalContentLength - 1;
  161. long rangeLength = 1 + rangeEnd - rangeStart;
  162. // Content-Length is the length of what we're serving, not the original content
  163. HttpListenerContext.Response.ContentLength64 = rangeLength;
  164. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  165. if (rangeStart > 0)
  166. {
  167. SourceStream.Position = rangeStart;
  168. }
  169. await SourceStream.CopyToAsync(responseStream);
  170. }
  171. /// <summary>
  172. /// Serves a partial range request where the total content length is not known
  173. /// </summary>
  174. private async Task ServePartialRangeRequestWithUnknownTotalContentLength(KeyValuePair<long, long?> requestedRange, Stream responseStream)
  175. {
  176. // Read the entire stream so that we can determine the length
  177. byte[] bytes = await ReadBytes(SourceStream, 0, null);
  178. long totalContentLength = bytes.LongLength;
  179. long rangeStart = requestedRange.Key;
  180. long rangeEnd = requestedRange.Value ?? (totalContentLength - 1);
  181. long rangeLength = 1 + rangeEnd - rangeStart;
  182. // Content-Length is the length of what we're serving, not the original content
  183. HttpListenerContext.Response.ContentLength64 = rangeLength;
  184. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  185. await responseStream.WriteAsync(bytes, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength));
  186. }
  187. /// <summary>
  188. /// Serves a partial range request where the total content length is already known
  189. /// </summary>
  190. private async Task ServePartialRangeRequestWithKnownTotalContentLength(KeyValuePair<long, long?> requestedRange, Stream responseStream)
  191. {
  192. long totalContentLength = TotalContentLength.Value;
  193. long rangeStart = requestedRange.Key;
  194. long rangeEnd = requestedRange.Value ?? (totalContentLength - 1);
  195. long rangeLength = 1 + rangeEnd - rangeStart;
  196. // Only read the bytes we need
  197. byte[] bytes = await ReadBytes(SourceStream, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength));
  198. // Content-Length is the length of what we're serving, not the original content
  199. HttpListenerContext.Response.ContentLength64 = rangeLength;
  200. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  201. await responseStream.WriteAsync(bytes, 0, Convert.ToInt32(rangeLength));
  202. }
  203. /// <summary>
  204. /// Reads bytes from a stream
  205. /// </summary>
  206. /// <param name="input">The input stream</param>
  207. /// <param name="start">The starting position</param>
  208. /// <param name="count">The number of bytes to read, or null to read to the end.</param>
  209. private async Task<byte[]> ReadBytes(Stream input, int start, int? count)
  210. {
  211. if (start > 0)
  212. {
  213. input.Position = start;
  214. }
  215. if (count == null)
  216. {
  217. byte[] buffer = new byte[16 * 1024];
  218. using (MemoryStream ms = new MemoryStream())
  219. {
  220. int read;
  221. while ((read = await input.ReadAsync(buffer, 0, buffer.Length)) > 0)
  222. {
  223. await ms.WriteAsync(buffer, 0, read);
  224. }
  225. return ms.ToArray();
  226. }
  227. }
  228. else
  229. {
  230. byte[] buffer = new byte[count.Value];
  231. using (MemoryStream ms = new MemoryStream())
  232. {
  233. int read = await input.ReadAsync(buffer, 0, buffer.Length);
  234. await ms.WriteAsync(buffer, 0, read);
  235. return ms.ToArray();
  236. }
  237. }
  238. }
  239. }
  240. }