BaseHandler.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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.Net;
  7. namespace MediaBrowser.Common.Net.Handlers
  8. {
  9. public abstract class BaseHandler
  10. {
  11. /// <summary>
  12. /// Response headers
  13. /// </summary>
  14. public IDictionary<string, string> Headers = new Dictionary<string, string>();
  15. private Stream CompressedStream { get; set; }
  16. public virtual bool UseChunkedEncoding
  17. {
  18. get
  19. {
  20. return true;
  21. }
  22. }
  23. public virtual long? ContentLength
  24. {
  25. get
  26. {
  27. return null;
  28. }
  29. }
  30. /// <summary>
  31. /// Returns true or false indicating if the handler writes to the stream asynchronously.
  32. /// If so the subclass will be responsible for disposing the stream when complete.
  33. /// </summary>
  34. protected virtual bool IsAsyncHandler
  35. {
  36. get
  37. {
  38. return false;
  39. }
  40. }
  41. /// <summary>
  42. /// The action to write the response to the output stream
  43. /// </summary>
  44. public Action<Stream> WriteStream
  45. {
  46. get
  47. {
  48. return s =>
  49. {
  50. WriteReponse(s);
  51. if (!IsAsyncHandler)
  52. {
  53. DisposeResponseStream();
  54. }
  55. };
  56. }
  57. }
  58. /// <summary>
  59. /// The original RequestContext
  60. /// </summary>
  61. public RequestContext RequestContext { get; set; }
  62. /// <summary>
  63. /// The original QueryString
  64. /// </summary>
  65. protected NameValueCollection QueryString
  66. {
  67. get
  68. {
  69. return RequestContext.Request.QueryString;
  70. }
  71. }
  72. /// <summary>
  73. /// Gets the MIME type to include in the response headers
  74. /// </summary>
  75. public abstract string ContentType { get; }
  76. /// <summary>
  77. /// Gets the status code to include in the response headers
  78. /// </summary>
  79. public virtual int StatusCode
  80. {
  81. get
  82. {
  83. return 200;
  84. }
  85. }
  86. /// <summary>
  87. /// Gets the cache duration to include in the response headers
  88. /// </summary>
  89. public virtual TimeSpan CacheDuration
  90. {
  91. get
  92. {
  93. return TimeSpan.FromTicks(0);
  94. }
  95. }
  96. /// <summary>
  97. /// Gets the last date modified of the content being returned, if this can be determined.
  98. /// This will be used to invalidate the cache, so it's not needed if CacheDuration is 0.
  99. /// </summary>
  100. public virtual DateTime? LastDateModified
  101. {
  102. get
  103. {
  104. return null;
  105. }
  106. }
  107. public virtual bool CompressResponse
  108. {
  109. get
  110. {
  111. return true;
  112. }
  113. }
  114. private bool ClientSupportsCompression
  115. {
  116. get
  117. {
  118. string enc = RequestContext.Request.Headers["Accept-Encoding"] ?? string.Empty;
  119. return enc.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1 || enc.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1;
  120. }
  121. }
  122. private string CompressionMethod
  123. {
  124. get
  125. {
  126. string enc = RequestContext.Request.Headers["Accept-Encoding"] ?? string.Empty;
  127. if (enc.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1)
  128. {
  129. return "deflate";
  130. }
  131. if (enc.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
  132. {
  133. return "gzip";
  134. }
  135. return null;
  136. }
  137. }
  138. protected virtual void PrepareResponseBeforeWriteOutput(HttpListenerResponse response)
  139. {
  140. // Don't force this to true. HttpListener will default it to true if supported by the client.
  141. if (!UseChunkedEncoding)
  142. {
  143. response.SendChunked = false;
  144. }
  145. if (ContentLength.HasValue)
  146. {
  147. response.ContentLength64 = ContentLength.Value;
  148. }
  149. if (CompressResponse && ClientSupportsCompression)
  150. {
  151. response.AddHeader("Content-Encoding", CompressionMethod);
  152. }
  153. TimeSpan cacheDuration = CacheDuration;
  154. if (cacheDuration.Ticks > 0)
  155. {
  156. CacheResponse(response, cacheDuration, LastDateModified);
  157. }
  158. }
  159. private void CacheResponse(HttpListenerResponse response, TimeSpan duration, DateTime? dateModified)
  160. {
  161. DateTime lastModified = dateModified ?? DateTime.Now;
  162. response.Headers[HttpResponseHeader.CacheControl] = "public, max-age=" + Convert.ToInt32(duration.TotalSeconds);
  163. response.Headers[HttpResponseHeader.Expires] = DateTime.Now.Add(duration).ToString("r");
  164. response.Headers[HttpResponseHeader.LastModified] = lastModified.ToString("r");
  165. }
  166. private void WriteReponse(Stream stream)
  167. {
  168. PrepareResponseBeforeWriteOutput(RequestContext.Response);
  169. if (CompressResponse && ClientSupportsCompression)
  170. {
  171. if (CompressionMethod.Equals("deflate", StringComparison.OrdinalIgnoreCase))
  172. {
  173. CompressedStream = new DeflateStream(stream, CompressionLevel.Fastest, false);
  174. }
  175. else
  176. {
  177. CompressedStream = new GZipStream(stream, CompressionLevel.Fastest, false);
  178. }
  179. WriteResponseToOutputStream(CompressedStream);
  180. }
  181. else
  182. {
  183. WriteResponseToOutputStream(stream);
  184. }
  185. }
  186. protected abstract void WriteResponseToOutputStream(Stream stream);
  187. protected void DisposeResponseStream()
  188. {
  189. if (CompressedStream != null)
  190. {
  191. CompressedStream.Dispose();
  192. }
  193. RequestContext.Response.OutputStream.Dispose();
  194. }
  195. }
  196. }