StaticFileHandler.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. protected override bool IsAsyncHandler
  109. {
  110. get
  111. {
  112. return true;
  113. }
  114. }
  115. public override string ContentType
  116. {
  117. get
  118. {
  119. return MimeTypes.GetMimeType(Path);
  120. }
  121. }
  122. protected async override void WriteResponseToOutputStream(Stream stream)
  123. {
  124. try
  125. {
  126. if (FileStream != null)
  127. {
  128. if (IsRangeRequest)
  129. {
  130. KeyValuePair<long, long?> requestedRange = RequestedRanges.First();
  131. // If the requested range is "0-" and we know the total length, we can optimize by avoiding having to buffer the content into memory
  132. if (requestedRange.Value == null && TotalContentLength != null)
  133. {
  134. await ServeCompleteRangeRequest(requestedRange, stream);
  135. }
  136. else if (TotalContentLength.HasValue)
  137. {
  138. // This will have to buffer a portion of the content into memory
  139. await ServePartialRangeRequestWithKnownTotalContentLength(requestedRange, stream);
  140. }
  141. else
  142. {
  143. // This will have to buffer the entire content into memory
  144. await ServePartialRangeRequestWithUnknownTotalContentLength(requestedRange, stream);
  145. }
  146. }
  147. else
  148. {
  149. await FileStream.CopyToAsync(stream);
  150. }
  151. }
  152. }
  153. catch (Exception ex)
  154. {
  155. Logger.LogException("WriteResponseToOutputStream", ex);
  156. }
  157. finally
  158. {
  159. if (FileStream != null)
  160. {
  161. FileStream.Dispose();
  162. }
  163. DisposeResponseStream();
  164. }
  165. }
  166. /// <summary>
  167. /// Handles a range request of "bytes=0-"
  168. /// This will serve the complete content and add the content-range header
  169. /// </summary>
  170. private async Task ServeCompleteRangeRequest(KeyValuePair<long, long?> requestedRange, Stream responseStream)
  171. {
  172. long totalContentLength = TotalContentLength.Value;
  173. long rangeStart = requestedRange.Key;
  174. long rangeEnd = totalContentLength - 1;
  175. long rangeLength = 1 + rangeEnd - rangeStart;
  176. // Content-Length is the length of what we're serving, not the original content
  177. HttpListenerContext.Response.ContentLength64 = rangeLength;
  178. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  179. if (rangeStart > 0)
  180. {
  181. FileStream.Position = rangeStart;
  182. }
  183. await FileStream.CopyToAsync(responseStream);
  184. }
  185. /// <summary>
  186. /// Serves a partial range request where the total content length is not known
  187. /// </summary>
  188. private async Task ServePartialRangeRequestWithUnknownTotalContentLength(KeyValuePair<long, long?> requestedRange, Stream responseStream)
  189. {
  190. // Read the entire stream so that we can determine the length
  191. byte[] bytes = await ReadBytes(FileStream, 0, null);
  192. long totalContentLength = bytes.LongLength;
  193. long rangeStart = requestedRange.Key;
  194. long rangeEnd = requestedRange.Value ?? (totalContentLength - 1);
  195. long rangeLength = 1 + rangeEnd - rangeStart;
  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, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength));
  200. }
  201. /// <summary>
  202. /// Serves a partial range request where the total content length is already known
  203. /// </summary>
  204. private async Task ServePartialRangeRequestWithKnownTotalContentLength(KeyValuePair<long, long?> requestedRange, Stream responseStream)
  205. {
  206. long totalContentLength = TotalContentLength.Value;
  207. long rangeStart = requestedRange.Key;
  208. long rangeEnd = requestedRange.Value ?? (totalContentLength - 1);
  209. long rangeLength = 1 + rangeEnd - rangeStart;
  210. // Only read the bytes we need
  211. byte[] bytes = await ReadBytes(FileStream, Convert.ToInt32(rangeStart), Convert.ToInt32(rangeLength));
  212. // Content-Length is the length of what we're serving, not the original content
  213. HttpListenerContext.Response.ContentLength64 = rangeLength;
  214. HttpListenerContext.Response.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", rangeStart, rangeEnd, totalContentLength);
  215. await responseStream.WriteAsync(bytes, 0, Convert.ToInt32(rangeLength));
  216. }
  217. /// <summary>
  218. /// Reads bytes from a stream
  219. /// </summary>
  220. /// <param name="input">The input stream</param>
  221. /// <param name="start">The starting position</param>
  222. /// <param name="count">The number of bytes to read, or null to read to the end.</param>
  223. private async Task<byte[]> ReadBytes(Stream input, int start, int? count)
  224. {
  225. if (start > 0)
  226. {
  227. input.Position = start;
  228. }
  229. if (count == null)
  230. {
  231. byte[] buffer = new byte[16 * 1024];
  232. using (MemoryStream ms = new MemoryStream())
  233. {
  234. int read;
  235. while ((read = await input.ReadAsync(buffer, 0, buffer.Length)) > 0)
  236. {
  237. await ms.WriteAsync(buffer, 0, read);
  238. }
  239. return ms.ToArray();
  240. }
  241. }
  242. else
  243. {
  244. byte[] buffer = new byte[count.Value];
  245. using (MemoryStream ms = new MemoryStream())
  246. {
  247. int read = await input.ReadAsync(buffer, 0, buffer.Length);
  248. await ms.WriteAsync(buffer, 0, read);
  249. return ms.ToArray();
  250. }
  251. }
  252. }
  253. }
  254. }