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