BaseHandler.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. string url = ctx.Request.Url.ToString();
  145. Logger.LogInfo("Http Server received request at: " + url);
  146. Logger.LogInfo("Http Headers: " + string.Join(",", ctx.Request.Headers.AllKeys.Select(k => k + "=" + ctx.Request.Headers[k])));
  147. ctx.Response.AddHeader("Access-Control-Allow-Origin", "*");
  148. ctx.Response.KeepAlive = true;
  149. try
  150. {
  151. if (SupportsByteRangeRequests && IsRangeRequest)
  152. {
  153. ctx.Response.Headers["Accept-Ranges"] = "bytes";
  154. }
  155. // Set the initial status code
  156. // When serving a range request, we need to return status code 206 to indicate a partial response body
  157. StatusCode = SupportsByteRangeRequests && IsRangeRequest ? 206 : 200;
  158. ctx.Response.ContentType = await GetContentType().ConfigureAwait(false);
  159. TimeSpan cacheDuration = CacheDuration;
  160. DateTime? lastDateModified = await GetLastDateModified().ConfigureAwait(false);
  161. if (ctx.Request.Headers.AllKeys.Contains("If-Modified-Since"))
  162. {
  163. DateTime ifModifiedSince;
  164. if (DateTime.TryParse(ctx.Request.Headers["If-Modified-Since"], out ifModifiedSince))
  165. {
  166. // If the cache hasn't expired yet just return a 304
  167. if (IsCacheValid(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified))
  168. {
  169. StatusCode = 304;
  170. }
  171. }
  172. }
  173. await PrepareResponse().ConfigureAwait(false);
  174. Logger.LogInfo("Responding with status code {0} for url {1}", StatusCode, url);
  175. if (IsResponseValid)
  176. {
  177. bool compressResponse = ShouldCompressResponse(ctx.Response.ContentType) && ClientSupportsCompression;
  178. await ProcessUncachedRequest(ctx, compressResponse, cacheDuration, lastDateModified).ConfigureAwait(false);
  179. }
  180. else
  181. {
  182. ctx.Response.StatusCode = StatusCode;
  183. ctx.Response.SendChunked = false;
  184. }
  185. }
  186. catch (Exception ex)
  187. {
  188. // It might be too late if some response data has already been transmitted, but try to set this
  189. ctx.Response.StatusCode = 500;
  190. Logger.LogException(ex);
  191. }
  192. finally
  193. {
  194. DisposeResponseStream();
  195. }
  196. }
  197. private async Task ProcessUncachedRequest(HttpListenerContext ctx, bool compressResponse, TimeSpan cacheDuration, DateTime? lastDateModified)
  198. {
  199. long? totalContentLength = TotalContentLength;
  200. // By default, use chunked encoding if we don't know the content length
  201. bool useChunkedEncoding = UseChunkedEncoding == null ? (totalContentLength == null) : UseChunkedEncoding.Value;
  202. // Don't force this to true. HttpListener will default it to true if supported by the client.
  203. if (!useChunkedEncoding)
  204. {
  205. ctx.Response.SendChunked = false;
  206. }
  207. // Set the content length, if we know it
  208. if (totalContentLength.HasValue)
  209. {
  210. ctx.Response.ContentLength64 = totalContentLength.Value;
  211. }
  212. // Add the compression header
  213. if (compressResponse)
  214. {
  215. ctx.Response.AddHeader("Content-Encoding", CompressionMethod);
  216. }
  217. // Add caching headers
  218. if (cacheDuration.Ticks > 0)
  219. {
  220. CacheResponse(ctx.Response, cacheDuration, lastDateModified);
  221. }
  222. // Set the status code
  223. ctx.Response.StatusCode = StatusCode;
  224. if (IsResponseValid)
  225. {
  226. // Finally, write the response data
  227. Stream outputStream = ctx.Response.OutputStream;
  228. if (compressResponse)
  229. {
  230. if (CompressionMethod.Equals("deflate", StringComparison.OrdinalIgnoreCase))
  231. {
  232. CompressedStream = new DeflateStream(outputStream, CompressionLevel.Fastest, false);
  233. }
  234. else
  235. {
  236. CompressedStream = new GZipStream(outputStream, CompressionLevel.Fastest, false);
  237. }
  238. outputStream = CompressedStream;
  239. }
  240. await WriteResponseToOutputStream(outputStream).ConfigureAwait(false);
  241. }
  242. else
  243. {
  244. ctx.Response.SendChunked = false;
  245. }
  246. }
  247. private void CacheResponse(HttpListenerResponse response, TimeSpan duration, DateTime? dateModified)
  248. {
  249. DateTime now = DateTime.UtcNow;
  250. DateTime lastModified = dateModified ?? now;
  251. response.Headers[HttpResponseHeader.CacheControl] = "public, max-age=" + Convert.ToInt32(duration.TotalSeconds);
  252. response.Headers[HttpResponseHeader.Expires] = now.Add(duration).ToString("r");
  253. response.Headers[HttpResponseHeader.LastModified] = lastModified.ToString("r");
  254. }
  255. /// <summary>
  256. /// Gives subclasses a chance to do any prep work, and also to validate data and set an error status code, if needed
  257. /// </summary>
  258. protected virtual Task PrepareResponse()
  259. {
  260. return Task.FromResult<object>(null);
  261. }
  262. protected abstract Task WriteResponseToOutputStream(Stream stream);
  263. protected virtual void DisposeResponseStream()
  264. {
  265. if (CompressedStream != null)
  266. {
  267. CompressedStream.Dispose();
  268. }
  269. HttpListenerContext.Response.OutputStream.Dispose();
  270. }
  271. private bool IsCacheValid(DateTime ifModifiedSince, TimeSpan cacheDuration, DateTime? dateModified)
  272. {
  273. if (dateModified.HasValue)
  274. {
  275. DateTime lastModified = NormalizeDateForComparison(dateModified.Value);
  276. ifModifiedSince = NormalizeDateForComparison(ifModifiedSince);
  277. return lastModified <= ifModifiedSince;
  278. }
  279. DateTime cacheExpirationDate = ifModifiedSince.Add(cacheDuration);
  280. if (DateTime.UtcNow < cacheExpirationDate)
  281. {
  282. return true;
  283. }
  284. return false;
  285. }
  286. /// <summary>
  287. /// When the browser sends the IfModifiedDate, it's precision is limited to seconds, so this will account for that
  288. /// </summary>
  289. private DateTime NormalizeDateForComparison(DateTime date)
  290. {
  291. return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
  292. }
  293. protected virtual long? GetTotalContentLength()
  294. {
  295. return null;
  296. }
  297. protected virtual Task<DateTime?> GetLastDateModified()
  298. {
  299. DateTime? value = null;
  300. return Task.FromResult<DateTime?>(value);
  301. }
  302. private bool IsResponseValid
  303. {
  304. get
  305. {
  306. return StatusCode == 200 || StatusCode == 206;
  307. }
  308. }
  309. }
  310. }