BaseHandler.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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 string ContentType { get; }
  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. private bool _LastDateModifiedDiscovered = false;
  114. private DateTime? _LastDateModified = null;
  115. /// <summary>
  116. /// Gets the last date modified of the content being returned, if this can be determined.
  117. /// This will be used to invalidate the cache, so it's not needed if CacheDuration is 0.
  118. /// </summary>
  119. public DateTime? LastDateModified
  120. {
  121. get
  122. {
  123. if (!_LastDateModifiedDiscovered)
  124. {
  125. _LastDateModified = GetLastDateModified();
  126. }
  127. return _LastDateModified;
  128. }
  129. }
  130. public virtual bool CompressResponse
  131. {
  132. get
  133. {
  134. return true;
  135. }
  136. }
  137. private bool ClientSupportsCompression
  138. {
  139. get
  140. {
  141. string enc = HttpListenerContext.Request.Headers["Accept-Encoding"] ?? string.Empty;
  142. return enc.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1 || enc.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1;
  143. }
  144. }
  145. private string CompressionMethod
  146. {
  147. get
  148. {
  149. string enc = HttpListenerContext.Request.Headers["Accept-Encoding"] ?? string.Empty;
  150. if (enc.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) != -1)
  151. {
  152. return "deflate";
  153. }
  154. if (enc.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
  155. {
  156. return "gzip";
  157. }
  158. return null;
  159. }
  160. }
  161. public virtual void ProcessRequest(HttpListenerContext ctx)
  162. {
  163. HttpListenerContext = ctx;
  164. Logger.LogInfo("Http Server received request at: " + ctx.Request.Url.ToString());
  165. Logger.LogInfo("Http Headers: " + string.Join(",", ctx.Request.Headers.AllKeys.Select(k => k + "=" + ctx.Request.Headers[k])));
  166. ctx.Response.AddHeader("Access-Control-Allow-Origin", "*");
  167. ctx.Response.KeepAlive = true;
  168. if (SupportsByteRangeRequests && IsRangeRequest)
  169. {
  170. ctx.Response.Headers["Accept-Ranges"] = "bytes";
  171. }
  172. // Set the initial status code
  173. // When serving a range request, we need to return status code 206 to indicate a partial response body
  174. StatusCode = SupportsByteRangeRequests && IsRangeRequest ? 206 : 200;
  175. ctx.Response.ContentType = ContentType;
  176. TimeSpan cacheDuration = CacheDuration;
  177. if (ctx.Request.Headers.AllKeys.Contains("If-Modified-Since"))
  178. {
  179. DateTime ifModifiedSince;
  180. if (DateTime.TryParse(ctx.Request.Headers["If-Modified-Since"].Replace(" GMT", string.Empty), out ifModifiedSince))
  181. {
  182. // If the cache hasn't expired yet just return a 304
  183. if (IsCacheValid(ifModifiedSince, cacheDuration, LastDateModified))
  184. {
  185. StatusCode = 304;
  186. }
  187. }
  188. }
  189. if (StatusCode == 200 || StatusCode == 206)
  190. {
  191. ProcessUncachedResponse(ctx, cacheDuration);
  192. }
  193. else
  194. {
  195. ctx.Response.StatusCode = StatusCode;
  196. ctx.Response.SendChunked = false;
  197. DisposeResponseStream();
  198. }
  199. }
  200. private async void ProcessUncachedResponse(HttpListenerContext ctx, TimeSpan cacheDuration)
  201. {
  202. long? totalContentLength = TotalContentLength;
  203. // By default, use chunked encoding if we don't know the content length
  204. bool useChunkedEncoding = UseChunkedEncoding == null ? (totalContentLength == null) : UseChunkedEncoding.Value;
  205. // Don't force this to true. HttpListener will default it to true if supported by the client.
  206. if (!useChunkedEncoding)
  207. {
  208. ctx.Response.SendChunked = false;
  209. }
  210. // Set the content length, if we know it
  211. if (totalContentLength.HasValue)
  212. {
  213. ctx.Response.ContentLength64 = totalContentLength.Value;
  214. }
  215. // Add the compression header
  216. if (CompressResponse && ClientSupportsCompression)
  217. {
  218. ctx.Response.AddHeader("Content-Encoding", CompressionMethod);
  219. }
  220. // Add caching headers
  221. if (cacheDuration.Ticks > 0)
  222. {
  223. CacheResponse(ctx.Response, cacheDuration, LastDateModified);
  224. }
  225. // Set the status code
  226. ctx.Response.StatusCode = StatusCode;
  227. if (StatusCode == 200 || StatusCode == 206)
  228. {
  229. // Finally, write the response data
  230. Stream outputStream = ctx.Response.OutputStream;
  231. if (CompressResponse && ClientSupportsCompression)
  232. {
  233. if (CompressionMethod.Equals("deflate", StringComparison.OrdinalIgnoreCase))
  234. {
  235. CompressedStream = new DeflateStream(outputStream, CompressionLevel.Fastest, false);
  236. }
  237. else
  238. {
  239. CompressedStream = new GZipStream(outputStream, CompressionLevel.Fastest, false);
  240. }
  241. outputStream = CompressedStream;
  242. }
  243. try
  244. {
  245. await WriteResponseToOutputStream(outputStream);
  246. }
  247. catch (Exception ex)
  248. {
  249. Logger.LogException(ex);
  250. }
  251. finally
  252. {
  253. DisposeResponseStream();
  254. }
  255. }
  256. else
  257. {
  258. ctx.Response.SendChunked = false;
  259. DisposeResponseStream();
  260. }
  261. }
  262. private void CacheResponse(HttpListenerResponse response, TimeSpan duration, DateTime? dateModified)
  263. {
  264. DateTime lastModified = dateModified ?? DateTime.Now;
  265. response.Headers[HttpResponseHeader.CacheControl] = "public, max-age=" + Convert.ToInt32(duration.TotalSeconds);
  266. response.Headers[HttpResponseHeader.Expires] = DateTime.Now.Add(duration).ToString("r");
  267. response.Headers[HttpResponseHeader.LastModified] = lastModified.ToString("r");
  268. }
  269. protected abstract Task WriteResponseToOutputStream(Stream stream);
  270. private void DisposeResponseStream()
  271. {
  272. if (CompressedStream != null)
  273. {
  274. CompressedStream.Dispose();
  275. }
  276. HttpListenerContext.Response.OutputStream.Dispose();
  277. }
  278. private bool IsCacheValid(DateTime ifModifiedSince, TimeSpan cacheDuration, DateTime? dateModified)
  279. {
  280. if (dateModified.HasValue)
  281. {
  282. DateTime lastModified = NormalizeDateForComparison(dateModified.Value);
  283. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  284. return lastModified <= ifModifiedSince;
  285. }
  286. DateTime cacheExpirationDate = ifModifiedSince.Add(cacheDuration);
  287. if (DateTime.Now < cacheExpirationDate)
  288. {
  289. return true;
  290. }
  291. return false;
  292. }
  293. /// <summary>
  294. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  295. /// </summary>
  296. private DateTime NormalizeDateForComparison(DateTime date)
  297. {
  298. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second);
  299. }
  300. protected virtual long? GetTotalContentLength()
  301. {
  302. return null;
  303. }
  304. protected virtual DateTime? GetLastDateModified()
  305. {
  306. return null;
  307. }
  308. }
  309. }