2
0

StaticFileHandler.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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 ShouldCompressResponse(string contentType)
  75. {
  76. // Can't compress these
  77. if (IsRangeRequest)
  78. {
  79. return false;
  80. }
  81. // Don't compress media
  82. if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  83. {
  84. return false;
  85. }
  86. // It will take some work to support compression within this handler
  87. return false;
  88. }
  89. protected override long? GetTotalContentLength()
  90. {
  91. return SourceStream.Length;
  92. }
  93. protected override Task<DateTime?> GetLastDateModified()
  94. {
  95. return Task.Run<DateTime?>(() =>
  96. {
  97. EnsureSourceStream();
  98. if (SourceStream == null)
  99. {
  100. return null;
  101. }
  102. return File.GetLastWriteTime(Path);
  103. });
  104. }
  105. public override Task<string> GetContentType()
  106. {
  107. return Task.Run(() =>
  108. {
  109. return MimeTypes.GetMimeType(Path);
  110. });
  111. }
  112. protected override Task PrepareResponse()
  113. {
  114. return Task.Run(() => { EnsureSourceStream(); });
  115. }
  116. protected async 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. await ServeCompleteRangeRequest(requestedRange, stream);
  125. }
  126. else if (TotalContentLength.HasValue)
  127. {
  128. // This will have to buffer a portion of the content into memory
  129. await ServePartialRangeRequestWithKnownTotalContentLength(requestedRange, stream);
  130. }
  131. else
  132. {
  133. // This will have to buffer the entire content into memory
  134. await ServePartialRangeRequestWithUnknownTotalContentLength(requestedRange, stream);
  135. }
  136. }
  137. else
  138. {
  139. await 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 async 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. await 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);
  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));
  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));
  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));
  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)) > 0)
  220. {
  221. await ms.WriteAsync(buffer, 0, read);
  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);
  232. await ms.WriteAsync(buffer, 0, read);
  233. return ms.ToArray();
  234. }
  235. }
  236. }
  237. }
  238. }