BaseHandler.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.IO;
  5. using System.IO.Compression;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Common.Logging;
  10. namespace MediaBrowser.Common.Net.Handlers
  11. {
  12. public abstract class BaseHandler
  13. {
  14. private Stream CompressedStream { get; set; }
  15. public virtual bool? UseChunkedEncoding
  16. {
  17. get
  18. {
  19. return null;
  20. }
  21. }
  22. private bool _TotalContentLengthDiscovered = false;
  23. private long? _TotalContentLength = null;
  24. public long? TotalContentLength
  25. {
  26. get
  27. {
  28. if (!_TotalContentLengthDiscovered)
  29. {
  30. _TotalContentLength = GetTotalContentLength();
  31. }
  32. return _TotalContentLength;
  33. }
  34. }
  35. protected virtual bool SupportsByteRangeRequests
  36. {
  37. get
  38. {
  39. return false;
  40. }
  41. }
  42. /// <summary>
  43. /// The original HttpListenerContext
  44. /// </summary>
  45. protected HttpListenerContext HttpListenerContext { get; set; }
  46. /// <summary>
  47. /// The original QueryString
  48. /// </summary>
  49. protected NameValueCollection QueryString
  50. {
  51. get
  52. {
  53. return HttpListenerContext.Request.QueryString;
  54. }
  55. }
  56. protected List<KeyValuePair<long, long?>> _RequestedRanges = null;
  57. protected IEnumerable<KeyValuePair<long, long?>> RequestedRanges
  58. {
  59. get
  60. {
  61. if (_RequestedRanges == null)
  62. {
  63. _RequestedRanges = new List<KeyValuePair<long, long?>>();
  64. if (IsRangeRequest)
  65. {
  66. // Example: bytes=0-,32-63
  67. string[] ranges = HttpListenerContext.Request.Headers["Range"].Split('=')[1].Split(',');
  68. foreach (string range in ranges)
  69. {
  70. string[] vals = range.Split('-');
  71. long start = 0;
  72. long? end = null;
  73. if (!string.IsNullOrEmpty(vals[0]))
  74. {
  75. start = long.Parse(vals[0]);
  76. }
  77. if (!string.IsNullOrEmpty(vals[1]))
  78. {
  79. end = long.Parse(vals[1]);
  80. }
  81. _RequestedRanges.Add(new KeyValuePair<long, long?>(start, end));
  82. }
  83. }
  84. }
  85. return _RequestedRanges;
  86. }
  87. }
  88. protected bool IsRangeRequest
  89. {
  90. get
  91. {
  92. return HttpListenerContext.Request.Headers.AllKeys.Contains("Range");
  93. }
  94. }
  95. /// <summary>
  96. /// Gets the MIME type to include in the response headers
  97. /// </summary>
  98. public abstract Task<string> GetContentType();
  99. /// <summary>
  100. /// Gets the status code to include in the response headers
  101. /// </summary>
  102. protected int StatusCode { get; set; }
  103. /// <summary>
  104. /// Gets the cache duration to include in the response headers
  105. /// </summary>
  106. public virtual TimeSpan CacheDuration
  107. {
  108. get
  109. {
  110. return TimeSpan.FromTicks(0);
  111. }
  112. }
  113. public virtual bool ShouldCompressResponse(string contentType)
  114. {
  115. return true;
  116. }
  117. private bool ClientSupportsCompression
  118. {
  119. get
  120. {
  121. string enc = HttpListenerContext.Request.Headers["Accept-Encoding"] ?? string.Empty;
  122. return enc.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1 || enc.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1;
  123. }
  124. }
  125. private string CompressionMethod
  126. {
  127. get
  128. {
  129. string enc = HttpListenerContext.Request.Headers["Accept-Encoding"] ?? string.Empty;
  130. if (enc.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1)
  131. {
  132. return "deflate";
  133. }
  134. if (enc.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
  135. {
  136. return "gzip";
  137. }
  138. return null;
  139. }
  140. }
  141. public virtual async Task ProcessRequest(HttpListenerContext ctx)
  142. {
  143. HttpListenerContext = ctx;
  144. Logger.LogInfo("Http Server received request at: " + ctx.Request.Url.ToString());
  145. Logger.LogInfo("Http Headers: " + string.Join(",", ctx.Request.Headers.AllKeys.Select(k => k + "=" + ctx.Request.Headers[k])));
  146. ctx.Response.AddHeader("Access-Control-Allow-Origin", "*");
  147. ctx.Response.KeepAlive = true;
  148. try
  149. {
  150. if (SupportsByteRangeRequests && IsRangeRequest)
  151. {
  152. ctx.Response.Headers["Accept-Ranges"] = "bytes";
  153. }
  154. // Set the initial status code
  155. // When serving a range request, we need to return status code 206 to indicate a partial response body
  156. StatusCode = SupportsByteRangeRequests && IsRangeRequest ? 206 : 200;
  157. ctx.Response.ContentType = await GetContentType().ConfigureAwait(false);
  158. TimeSpan cacheDuration = CacheDuration;
  159. DateTime? lastDateModified = await GetLastDateModified().ConfigureAwait(false);
  160. if (ctx.Request.Headers.AllKeys.Contains("If-Modified-Since"))
  161. {
  162. DateTime ifModifiedSince;
  163. if (DateTime.TryParse(ctx.Request.Headers["If-Modified-Since"].Replace(" GMT", string.Empty), out ifModifiedSince))
  164. {
  165. // If the cache hasn't expired yet just return a 304
  166. if (IsCacheValid(ifModifiedSince, cacheDuration, lastDateModified))
  167. {
  168. StatusCode = 304;
  169. }
  170. }
  171. }
  172. await PrepareResponse().ConfigureAwait(false);
  173. if (IsResponseValid)
  174. {
  175. bool compressResponse = ShouldCompressResponse(ctx.Response.ContentType) && ClientSupportsCompression;
  176. await ProcessUncachedRequest(ctx, compressResponse, cacheDuration, lastDateModified).ConfigureAwait(false);
  177. }
  178. else
  179. {
  180. ctx.Response.StatusCode = StatusCode;
  181. ctx.Response.SendChunked = false;
  182. }
  183. }
  184. catch (Exception ex)
  185. {
  186. // It might be too late if some response data has already been transmitted, but try to set this
  187. ctx.Response.StatusCode = 500;
  188. Logger.LogException(ex);
  189. }
  190. finally
  191. {
  192. DisposeResponseStream();
  193. }
  194. }
  195. private async Task ProcessUncachedRequest(HttpListenerContext ctx, bool compressResponse, TimeSpan cacheDuration, DateTime? lastDateModified)
  196. {
  197. long? totalContentLength = TotalContentLength;
  198. // By default, use chunked encoding if we don't know the content length
  199. bool useChunkedEncoding = UseChunkedEncoding == null ? (totalContentLength == null) : UseChunkedEncoding.Value;
  200. // Don't force this to true. HttpListener will default it to true if supported by the client.
  201. if (!useChunkedEncoding)
  202. {
  203. ctx.Response.SendChunked = false;
  204. }
  205. // Set the content length, if we know it
  206. if (totalContentLength.HasValue)
  207. {
  208. ctx.Response.ContentLength64 = totalContentLength.Value;
  209. }
  210. // Add the compression header
  211. if (compressResponse)
  212. {
  213. ctx.Response.AddHeader("Content-Encoding", CompressionMethod);
  214. }
  215. // Add caching headers
  216. if (cacheDuration.Ticks > 0)
  217. {
  218. CacheResponse(ctx.Response, cacheDuration, lastDateModified);
  219. }
  220. // Set the status code
  221. ctx.Response.StatusCode = StatusCode;
  222. if (IsResponseValid)
  223. {
  224. // Finally, write the response data
  225. Stream outputStream = ctx.Response.OutputStream;
  226. if (compressResponse)
  227. {
  228. if (CompressionMethod.Equals("deflate", StringComparison.OrdinalIgnoreCase))
  229. {
  230. CompressedStream = new DeflateStream(outputStream, CompressionLevel.Fastest, false);
  231. }
  232. else
  233. {
  234. CompressedStream = new GZipStream(outputStream, CompressionLevel.Fastest, false);
  235. }
  236. outputStream = CompressedStream;
  237. }
  238. await WriteResponseToOutputStream(outputStream).ConfigureAwait(false);
  239. }
  240. else
  241. {
  242. ctx.Response.SendChunked = false;
  243. }
  244. }
  245. private void CacheResponse(HttpListenerResponse response, TimeSpan duration, DateTime? dateModified)
  246. {
  247. DateTime lastModified = dateModified ?? DateTime.Now;
  248. response.Headers[HttpResponseHeader.CacheControl] = "public, max-age=" + Convert.ToInt32(duration.TotalSeconds);
  249. response.Headers[HttpResponseHeader.Expires] = DateTime.Now.Add(duration).ToString("r");
  250. response.Headers[HttpResponseHeader.LastModified] = lastModified.ToString("r");
  251. }
  252. /// <summary>
  253. /// Gives subclasses a chance to do any prep work, and also to validate data and set an error status code, if needed
  254. /// </summary>
  255. protected virtual Task PrepareResponse()
  256. {
  257. return Task.FromResult<object>(null);
  258. }
  259. protected abstract Task WriteResponseToOutputStream(Stream stream);
  260. protected virtual void DisposeResponseStream()
  261. {
  262. if (CompressedStream != null)
  263. {
  264. CompressedStream.Dispose();
  265. }
  266. HttpListenerContext.Response.OutputStream.Dispose();
  267. }
  268. private bool IsCacheValid(DateTime ifModifiedSince, TimeSpan cacheDuration, DateTime? dateModified)
  269. {
  270. if (dateModified.HasValue)
  271. {
  272. DateTime lastModified = NormalizeDateForComparison(dateModified.Value);
  273. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  274. return lastModified <= ifModifiedSince;
  275. }
  276. DateTime cacheExpirationDate = ifModifiedSince.Add(cacheDuration);
  277. if (DateTime.Now < cacheExpirationDate)
  278. {
  279. return true;
  280. }
  281. return false;
  282. }
  283. /// <summary>
  284. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  285. /// </summary>
  286. private DateTime NormalizeDateForComparison(DateTime date)
  287. {
  288. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second);
  289. }
  290. protected virtual long? GetTotalContentLength()
  291. {
  292. return null;
  293. }
  294. protected virtual Task<DateTime?> GetLastDateModified()
  295. {
  296. DateTime? value = null;
  297. return Task.FromResult<DateTime?>(value);
  298. }
  299. private bool IsResponseValid
  300. {
  301. get
  302. {
  303. return StatusCode == 200 || StatusCode == 206;
  304. }
  305. }
  306. }
  307. }