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